My Swing-Application sets the size of the JFrame via GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(), and all Elements are relative to this values, so basically the application adapts to the screen resolution.
Now I have a problem with my custom buttons. For now, I create three different ImageIcons (normal, rollover and pressed) and add them to the button. But naturally, if I run the application with a different resolution than 1920×1080 (which is my default), the buttons are too big.
I found this question (http://stackoverflow.com/questions/8234726/auto-resizing-jbutton-icon) and tried the solution by creating an Icon, put it on a Jlabel and add the label to the button, but nothing is displaid. Also, I do not need to resize the window.
What is the fastest and solution for this topic? An option would be to create all custom images individually for every resolution, add the x-value of the resolution at the end of the image name and make let’s say a switch case to check which image should be load, but I think this is a very expensive and time-consuming solution. Is there an efficient way to automatically size a loaded image to a certian size relative to the screen resolution?
If you have an
Image, you can invokegetScaledInstanceto retrieve a resized image.If you have an
ImageIcon,you can invokegetImage()on it, to retrieve anImageand then use the solution suggested above.getScaledInstancereturns anImagewhich you can wrap back into anImageIconand set on aJButtonor aJLabel.So, I would create my images with the highest resolution possible and then downscale them to the appropriate resolution.
Here is a small snippet (inspired from @mKorbel solution you started from):
Small note: it is not recommended to extend JFrame but I tried to stay as close as possible to the original code.