0

I'm new to Java and I'm experimenting with GUI. I'm trying to create an image that dynamically scales with the size of the window. What I've created to attempt this is very laggy and dysfunctional. My code fails to paint over previous images and seems very inefficient. Is there a better way to automatically scale an image with the size of the window?

My Code:

import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

public class DynamicImageScaleEx {
static JFrame frame;
static JLabel ImageLabel; 
static ImageIcon imageIcon;
    
    public static void main(String[] args) {
        new DynamicImageScaleEx();
                    frame.setVisible(true);     
        }
    
    public DynamicImageScaleEx() {
        frame = new JFrame();
        frame.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {
 imageIcon= new ImageIcon(new ImageIcon("image.png").getImage().getScaledInstance(frame.getWidth(), frame.getHeight(), Image.SCALE_SMOOTH));
 ImageLabel = new JLabel(imageIcon); 
 frame.getContentPane().add(ImageLabel);
            }});
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
         imageIcon = new ImageIcon(new ImageIcon("image.png").getImage().getScaledInstance(frame.getWidth(), frame.getHeight(), Image.SCALE_SMOOTH));
         ImageLabel = new JLabel(imageIcon);
        ImageLabel.setBounds(190, 126, 61, 16);
        frame.getContentPane().add(ImageLabel);
    }

}
Nerf
  • 1
  • 1
    1) Don't use static variables. That is not how the static keyword should be used 2) Don't use setBounds(). 3) There are a couple of different approaches for scaling an image a) you could use the [Stretch Icon](https://tips4java.wordpress.com/2012/03/31/stretch-icon/). It will automatically resize the image to fill the space available. b) do custom painting to paint the image as a background on a panel. You can check out the [Background Panel](https://tips4java.wordpress.com/2008/10/12/background-panel/). It gives multiple option on how to display the image in a panel. – camickr Aug 25 '20 at 23:20
  • For [example](https://stackoverflow.com/questions/12876615/how-do-i-resize-images-inside-an-application-when-the-application-window-is-resi/12876799#12876799), [example](https://stackoverflow.com/questions/22162398/how-to-set-a-background-picture-in-jpanel/22162430#22162430), [example](https://stackoverflow.com/questions/13166402/drawn-image-inside-panel-seems-to-have-wrong-x-y-offset/13168202#13168202) – MadProgrammer Aug 25 '20 at 23:48

0 Answers0