简体   繁体   中英

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.

您正在寻找JLabel's setIcon方法

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM