Search code examples
javaimageswingjlabelsetbounds

How to repaint Image after changing?


I have a JPanel, in which I have a JLabel, which contains an Image, like this:

JLabel imageLabel = new JLabel(new ImageIcon(image));

after that, I set the bounds of the imageLabel, like this:

//I want the Image to be in the middle of the screen!
imageLabel.setBounds((int) (screenSize.getWidth() / 2 - image.getWidth(null) / 2),
        (int) (screenSize.getHeight() / 2 - image.getHeight(null) / 2),
        image.getWidth(null), image.getHeight(null));

And then I add the imageLabel to the JPanel.

add(imageLabel);

Now I want to change the Image, by using a KeyEvent(the KeyEvent works). I think, it changes the Image(by using image = any other Image), but it doesn't change on the screen.
How can I achive that? I've tried to add revalidate() and repaint(); to the JPanel.


Solution

  • I think, it changes the Image(by using image = any other Image),

    That does nothing. All you have done is update the variable to point to a different image. You didn't actually add the image to the label.

    You need to reset the Icon of the label:

    label.setIcon( new ImageIcon(...) );