Yedya
Yedya

Reputation: 1

Change Image when an action is performed

How can I change my images when an action is performed? My images are stored in the project.

Declared images

image = new ImageIcon ("1.jpg");
image2 = new ImageIcon ("3.jpg");
image3 = new ImageIcon ("2.jpg");
picLabel = new JLabel(image);

ActionListener Class

public void actionPerformed(ActionEvent e){
    if(e.getSource().equals(A)) {
        image = new ImageIcon ("1.jpg");
        //picLabel = new JLabel(image); didn't work
    } else if(e.getSource().equals(B)) {
        image = new ImageIcon ("2.jpg");
        //picLabel = new JLabel(image2); didn't work
    } else if(e.getSource().equals(C)) {        
        image = new ImageIcon ("3.jpg");
        //picLabel = new JLabel(image3); didn't work
    }
}

Upvotes: 0

Views: 232

Answers (3)

Marv
Marv

Reputation: 3557

If you assign a new JLabel to the picLabel label, you create a new object that is not part of your UI. The existing JLabel in your UI is referenced by picLabel, so calling

picLabel.setIcon(image);

should set the Icon for the existing JLabel.

Upvotes: 1

Gumbo
Gumbo

Reputation: 1746

Keep a reference to picLabel in your class and in the action listener call picLabel.setIcon(new ImageIcon("Whatever.jpg")); to change the picture.

Upvotes: 0

cybersoft
cybersoft

Reputation: 1473

You must call

picLabel.setIcon(image);

Upvotes: 1

Related Questions