Browse for image file and display it using Java Swing

Each time a new image is selected, you’re creating components unnecessarily and in error here:

public void setTarget(File reference) {
    //....
    panel_1.setLayout(new BorderLayout(0, 0));
    panel_1.add(new JLabel(new ImageIcon(targetImg))); 
    setVisible(true);

Instead I would recommend that you have all these components created from the get-go, before any file/image has been selected, and then in this method, create an ImageIcon from the Image, and then simply use this Icon to set the Icon of an already existng JLabel rather than a new JLabel. This is done simply by calling myLabel.setIcon(new ImageIcon(targetImg));

Leave a Comment