I have read an image into a JLabel and scaled the image to the size of the JLabel like this:
File file = new File ("C:/Users/Me/Desktop/TestImages/test.jpg");
BufferedImage image = ImageIO.read(file);
Image scaledImage = image.getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_SMOOTH);
label.setIcon(new ImageIcon(scaledImage));
I'm using the provided GroupLayout and set the horizontal and vertical axes to "Auto-Resizable" (via Design view) so that the size of the JLabel auto-adjusts to the size of the JFrame whenever I change the window size.
Now I'd like to adjust the size of the image together with the size of the JLabel and here starts the trouble. I have added an event handler that responds to resizing the JFrame like this:
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
addScaledImage(); // executes the lines above
}
});
This works in theory but is extremely slow. So I tried adding the event handler to the JLabel instead of the JFrame but that leads to another issue: the image keeps expanding without any action being performed. Then I surrounded the JLabel with a JScrollPane and added the event handler to the JScrollPane. This works as long as I'm expanding the size of the JFrame. However, when I reduce the windows size, the image is not being reduced in size but instead stays the same.
Is there a more elegant way to integrate the event handler (maybe without help of a JScrollPane)?
How can I make my image/JLabel auto-resize together with any resizing event (increasing and decreasing the size of the JFrame)? Is another approach (e.g. another LayoutManager) maybe better suited for this?
Also, if I'd like to keep the height-to-width ratio of my image, is there a scaling method designated to this?