3

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.

Aaron
  • 992
  • 3
  • 15
  • 33

2 Answers2

3

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.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
0

call validate() instead of repaint()

K Adithyan
  • 386
  • 4
  • 12