java swing 窗口和控件自适应大小
本文记录java开发CS结构时怎么自适应屏幕大小以及控件跟随frame大小变化大小、位置和字体大小
需要注意:
1、代码必须放置在其构造方法中。如:我的frame1是我frame.java的名,则代码放置在方法“public Frame1() ”中。
2、放在控件初始化后的地方。
frame.java中Frame1() 方法中的代码:
//自动化页面大小--全屏 int fraWidth = this.getWidth();//frame的宽 int fraHeight = this.getHeight();//frame的高 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int screenWidth = screenSize.width; int screenHeight = screenSize.height; this.setSize(screenWidth, screenHeight); this.setLocation(0, 0); float proportionW = screenWidth/fraWidth; float proportionH = screenHeight/fraHeight; FrameShow.modifyComponentSize(this, proportionW,proportionH); this.toFront();
FrameShow.java中的modifyComponentSize(JFrame frame,float proportionW,float proportionH)方法
/** * frame中的控件自适应frame大小:改变大小位置和字体 * @param frame 要控制的窗体 * @param proportion 当前和原始的比例 */ public static void modifyComponentSize(JFrame frame,float proportionW,float proportionH){ try { Component[] components = frame.getRootPane().getContentPane().getComponents(); for(Component co:components) { // String a = co.getClass().getName();//获取类型名称 // if(a.equals("javax.swing.JLabel")) // { // } float locX = co.getX() * proportionW; float locY = co.getY() * proportionH; float width = co.getWidth() * proportionW; float height = co.getHeight() * proportionH; co.setLocation((int)locX, (int)locY); co.setSize((int)width, (int)height); int size = (int)(co.getFont().getSize() * proportionH); Font font = new Font(co.getFont().getFontName(), co.getFont().getStyle(), size); co.setFont(font); } } catch (Exception e) { // TODO: handle exception } }