I'm trying to write a panel with 3 vertical section in MigLayout: top growing, middle fixed and bottom growing.
The top is a JLabel with font-size-based-on-container-size. The middle is also a Jlabel, and the bottom is currently an empty JPanel.
Enlarging window is ok:
When I resize back the window, content doesn't resize back (note that the problem is not the font size, but the container width):
This problem exists only when in overrided method paint (see below) is called setFont on timer JLabel.
public class TabRace extends JPanel {
private JLabel timer;
public TabRace() {
super();
// Set the layout
this.setLayout(new MigLayout("","[grow]","[grow][][grow]"));
// Timer label
timer = new JLabel("00:00:00.000");
timer.setOpaque(true);
timer.setBackground(new Color(0, 0, 0));
timer.setForeground(new Color(255, 255, 255));
this.add(timer,"grow,wrap");
// Table label
JLabel tableCaption = new JLabel("Last Records:");
this.add(tableCaption,"wrap");
JPanel bottom = new JPanel();
this.add(bottom, "grow,wrap");
}
public void paint(Graphics g) {
super.paint(g);
// Thanks to coobird
// @see https://stackoverflow.com/questions/2715118/how-to-change-the-size-of-the-font-of-a-jlabel-to-take-the-maximum-size
Font labelFont = timer.getFont();
final int stringWidth = timer.getFontMetrics(labelFont).stringWidth(timer.getText());
final int componentWidth = timer.getWidth();
// Find out how much the font can grow in width.
double widthRatio = (double)componentWidth / (double)stringWidth;
int newFontSize = (int)(labelFont.getSize() * widthRatio);
int componentHeight = timer.getHeight();
// Pick a new font size so it will not be larger than the height of label.
int fontSizeToUse = Math.min(newFontSize, componentHeight);
// Set the label's font size to the newly determined size.
// REMOVING NEXT LINE AND RESIZING IS WORKING
timer.setFont(new Font(labelFont.getName(), Font.PLAIN, fontSizeToUse));
}
}
I've tried also to put JLabel inside JPanel. Any ideas?