DiscoStuIII
DiscoStuIII

Reputation: 21

How to change the image of a JLabel

I know this was answered a few times before, but the ones i found were answered with blocks of program specific code and i was having trouble discerning what specific code actually changed the image. I'm trying to change the jlabel image on my GUI during runtime by pushing a button.

public JPanel createContentPane (){
    JPanel totalGUI = new JPanel();
    totalGUI.setLayout(null);

    pictureArea = new JPanel();
    pictureArea.setLayout(null);
    pictureArea.setLocation(560, 0);
    pictureArea.setSize(860, 500);
    totalGUI.add(pictureArea);    

    picture = new JLabel(image);
    picture.setLocation(0, 0);
    picture.setSize(800, 800);
    picture.setHorizontalAlignment(0);
    pictureArea.add(picture);

    //skipping other code

    decision2 = new JButton("Next");
    decision2.setLocation(160, 20);
    decision2.setSize(70, 30);
    decision2.addActionListener(this);
    buttonPanel.add(decision2);

    return totalGUI;
}
public void actionPerformed(ActionEvent e) {
    //skipped other code
    else if(e.getSource() == decision2){
       //code i need for changing the image
    }
}

Thank you for any help you can provide.

Upvotes: 2

Views: 5165

Answers (2)

spiderman
spiderman

Reputation: 11112

Have you tried this ?

//code i need for changing the image call the function that has the JLabel defined, and pass the image_location eg: images/image.png

yourfunction(String imagelocation)
{

 BufferedImage bufImg=ImageIO.read(new File(image_location));
    jlabel.setIcon(new ImageIcon(bufImg));

}

reference:http://docs.oracle.com/javase/7/docs/api/

Upvotes: 0

Reimeus
Reimeus

Reputation: 159754

You're looking for JLabel's setIcon method

label.setIcon(new ImageIcon(getClass().getResource("/path/to/image.png")));

Upvotes: 4

Related Questions