Java: How to change an image in an image panel as determined by which radio button is selected

StackOverflow https://stackoverflow.com/questions/19426748

  •  01-07-2022
  •  | 
  •  

質問

I'm a java beginner, and my java skills suck on this. In my jframe, i have this jpanel(below) which draws the image. I want the image changed whenever a radiobutton(in another frame) fires an ItemEvent and click something like a save button that'll fire an ActionEvent. i intend this to be of use for a character-selecting interface, as in MMORPGs, etc. Image panel below is intended for weapon-selecting interface in my game.

class Weapons extends JPanel {

    private Image weaponimage = weapon2.getImage();

    @Override
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);

        g.drawImage(weaponimage, 0, 0,  this);
    }
}

weapon2 is an ImageIcon. thanks in advance.

役に立ちましたか?

解決

The simplest approach is not to have a custom panel at all, but use JLabel as the image container. Then you can change the image with:

label.setIcon(new ImageIcon(theNewWeaponImage));

Edit: since it looks like you already have Icons, you can use those directly:

label.setIcon(theNewWeaponIcon);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top