所以我要做的是调整JFrame中每个组件的字体大小,知道字体在启动时有不同的大小。
例如,我有一个字体大小为15的JButton和一个字体大小为20的JLabel:
button1.setFont(new Font("Arial", Font.PLAIN, 15));
label1.setFont(new Font("Arial", Font.PLAIN, 20));
我想要的结果是,如果窗口的大小调整为其宽度的两倍,则组件应该以相同的速率运行,因此JButton将为30,JLabel将为40。
我在JFrame上使用ComponentListener但我找不到如何操作。 这是我现在拥有的;如果只知道窗口的大小 BEFORE 它已经调整大小它已经有效了,但我不认为这是可能的。
以下是重写的componentResized方法:
@Override
public void componentResized(ComponentEvent arg0) {
Component[] components = ((JFrame)arg0.getComponent()).getComponents();
System.out.println(((Component) arg0.getSource()).getSize().getWidth());//How do I find the window's size before it was resized ?
//Getting standard window size
Dimension dimScreen = Toolkit.getDefaultToolkit().getScreenSize();
Dimension dimBaseWindow = new Dimension(dimScreen.width/2,dimScreen.height/2);
double baseWidth = dimBaseWindow.getWidth();
//Getting current window size
Dimension dimCurrentWindow = ((JFrame)arg0.getComponent()).getSize();
double currentWidth = dimCurrentWindow.getWidth();
System.out.println(currentWidth);
//Rate at which the font will be resized
double resizeRate = currentWidth/baseWidth;
resizeComponentsFonts(components, resizeRate, (int)currentWidth, (int)baseWidth);
}
resizeComponentsFonts方法:
public void resizeComponentsFonts(Component[] components, double resizeRate, int newWindowWidth, int baseWindowWidth) {
for(int i=0;i<components.length;i++) {
if(components[i] instanceof JPanel || components[i] instanceof JLayeredPane || components[i] instanceof JRootPane) {
resizeComponentsFonts(((Container)components[i]).getComponents(),resizeRate, newWindowWidth, baseWindowWidth);
}
else {
//System.out.println((double)components[i].getFont().getSize()/newWindowWidth*baseWindowWidth);
components[i].setFont(new Font(components[i].getFont().getFontName(),components[i].getFont().getStyle(),(int) (((double)components[i].getFont().getSize()/newWindowWidth*baseWindowWidth)*resizeRate)));
}
}
}