我知道之前已经回答了几次,但是我找到的那些回答了程序特定代码块,我无法辨别具体代码实际改变了什么图像。我想通过按下按钮在运行时更改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
}
}
感谢您提供任何帮助。
答案 0 :(得分:3)
您正在寻找JLabel's
setIcon
方法
label.setIcon(new ImageIcon(getClass().getResource("/path/to/image.png")));
答案 1 :(得分:0)
你试过这个吗?
//我需要更改图像的代码
调用已定义JLabel的函数,并传递image_location,例如:images/image.png
yourfunction(String imagelocation)
{
BufferedImage bufImg=ImageIO.read(new File(image_location));
jlabel.setIcon(new ImageIcon(bufImg));
}