So what I'm trying to do is to resize the font of every component in a JFrame knowing that the fonts have different sizes at launch.
For example, I would have a JButton with a font size of 15 and a JLabel with a font size of 20 :
button1.setFont(new Font("Arial", Font.PLAIN, 15));
label1.setFont(new Font("Arial", Font.PLAIN, 20));
The result I want here is that if the window is resized to twice its width, the components should follow at the same rate, so the JButton would be 30 and the JLabel would be 40.
I'm using a ComponentListener on the JFrame but I can't find how to do it. Here's what I currently have; if only I knew the window's size BEFORE it was resized it would already be working, but I don't think it's possible.
Here is the overridden componentResized method :
@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 method :
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)));
}
}
}