Exia0890
Exia0890

Reputation: 441

Swing change image with a button

I have 2 class defined this way :

public class Cartes extends JPanel
{
  private BufferedImage image;
  protected int tabC[] = new int[9];
  public int randomC ;

  public Cartes ()
  {

    ..........

    BufferedImage myPicture = null;

    try {
      myPicture = ImageIO.read(new File("images/"+randomC+".png"));
    } 
    catch (IOException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
    add( picLabel );
  }

  public void paintComponent(Graphics g)
  {
    super.paintComponent(g);
    g.drawImage(image, 0, 0, null); //
  }
}

Note : randomC is an integer generated in the constructor allowing me to choose at random an image .

AND

public class VueGeo extends JFrame
{
  public Cartes pan = new Cartes();
  private JButton bouton = new JButton("Change");

  public VueGeo()
  {

    ...

    container.add(pan, BorderLayout.CENTER);

    bouton.addActionListener(new BoutonListener ());

    ...

    this.setContentPane(container);

    this.setVisible(true);

  }

  class BoutonListener implements ActionListener
  {
    public void actionPerformed(ActionEvent arg0) {
      ????????
    }
  }
} 

The problem is I don't know what to put in actionPerformed in order to allow me to change image whenever i click on Change . Does someone has an idea please ?

Upvotes: 2

Views: 1881

Answers (1)

Name
Name

Reputation: 2045

Make a setter method in Cartes:

public void setImage(BufferedImage i)
{ image = i; }

Then, in actionPerformed,

cartes.setImage( (whatever image you would like) );
cartes.repaint();

Upvotes: 3

Related Questions