0

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.

1 Answers1

0

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(...) );
camickr
  • 321,443
  • 19
  • 166
  • 288
  • Does it than automaticly recalculate the bounds? –  Jan 23 '18 at 18:23
  • @Andy, try it. You learn by trying. Why would you think it would recalculate the bounds. You needed to manually calculate the bounds the first time, so what would you expect to happen the second time? – camickr Jan 23 '18 at 18:23
  • But than I should just copy everything into the `KeyListener`? –  Jan 23 '18 at 18:27
  • I've tried a few things and it turned out, that I only had to add these two things to the `KeyListener`: `image = newImage;` and `imageLabel.setIcon(new ImageIcon(image));`. –  Jan 23 '18 at 18:43
  • Great. You learn by experimenting. Swing will automatically revalidate() and repaint() a component when a property of the component is changed. So simply changing the Icon causes it to be repainted. Of course the label will only stay centered if the image is the same size. – camickr Jan 23 '18 at 18:46
  • But I've tried it out with different ImageSizes and I think it worked, without adding `setBounds()` again. But only one of the dimensions was different. But that doesn't change anything, does it? –  Jan 23 '18 at 19:00
  • If you have different size images then either 1) your are using a layout manager that is setting the size/location of each component, so the setBounds(..) doesn't do anything or 2) the image will not be centered because an image that is (500, 500) will need to be in a different location that an image that is (100, 100), in which case you need to reset the bounds. – camickr Jan 23 '18 at 19:25