Trying to learn Java Swing and have a mostly conceptual question:
I understand it is recommended to not hard-code sizes of components and instead let the LayoutManagers take care of resizing (e.g. due to resizable frame or different resolutions on different screens) components appropriately.
This seems to work for the components but I'm puzzled when it comes to the "contents" of the components as these seem to not change their size according to the changes in their component.
Examples: For me
the font size in a JTextArea does not seem to increase if the JTextArea does (as discussed in Maximize font size while keeping text within JTextField)
the size of an ImageIcon on a JButton does not resize when the JButton does (similar to resizing a ImageIcon in a JButton)
Wouldn't it be natural to have the contents in these components resize with their component (as a standard option in Swing)?
Would your solution be getting the size of the component when painting it and then resizing its content?
I tried that for 2., extending JButton and overriding getIcon() with something like this (as suggested in the link I believe):
@Override
public Icon getIcon() {
Icon icon=super.getIcon();
if(icon instanceof ImageIcon)
{
Image image=((ImageIcon)icon).getImage();
Image newimg = image.getScaledInstance(Math.max(this.getSize().width-10,1),Math.max(this.getSize().height-10,1), java.awt.Image.SCALE_SMOOTH);
icon=new ImageIcon(newimg);
}
return icon;
}
Regardless of the above conceptual question I'd also appreciate help regarding this concrete example. One problem with this implementation seems to be that the JButton's size can't decrease anymore once it contains the suitably sized icon.
Seems silly to do that for every possible type of component and content.