Aaron
Aaron

Reputation: 1016

Images Not Updating In Swing

I'm having a problem updating an Image in my GUI. Everything besides these methods is coded correctly because the Image appears when I write the code (from the "setImage" method below) in the initilize of the GUI.

I'm trying to get methods to update the image when a button is clicked. However, when the button is clicked, nothing changes. The method calls are correctly written in the MouseListener. All JLabels / Images are declared private so I can call them in the methods.

public void setImage(String path) {

    //path = "imageName.png"
    removeImageLabel();
    try {
        img = ImageIO.read(new File(path));
    } catch (IOException e) {
        e.printStackTrace();
    }
    imageLabel = new JLabel(new ImageIcon(img));
    imagePanel.add(imageLabel);
    imagePanel.repaint();
}

public void removeImageLabel() { //removes the current image from the GUI
    imagePanel.remove(imageLabel);
}

I have other methods that set elements based on button clicks, but this one doesn't seem to work. No error is thrown, but nothing is updated. What is wrong?

Note: I have added a println() to the method and it is called.

NEW: I added an image in the creation of the GUI and it displays, but it is never removed when the methods are called.

Upvotes: 3

Views: 1341

Answers (2)

trashgod
trashgod

Reputation: 205775

Instead of replacing the entire image component, consider updating the component's image in place, as shown in this example, or updating the label's icon in place, as shown here.

Upvotes: 3

K Adithyan
K Adithyan

Reputation: 396

call validate() instead of repaint()

Upvotes: 0

Related Questions