简体   繁体   English

如何更改JLabel的图像

[英]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. 我想通过按下按钮在运行时更改GUI上的jlabel图像。

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 //我需要更改图像的代码调用具有JLabel定义的函数,并传递images/image.png例如: 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/ 参考: http//docs.oracle.com/javase/7/docs/api/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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