2014-12-13 54 views
0

如何在执行操作时更改图像?我的图像存储在项目中。执行操作时更改图像

申报图像

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

的ActionListener类

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 
    } 
} 

回答

1

如果您将新的JLabel分配给picLabel标签,则会创建一个不属于您的用户界面的新对象。在UI现有JLabelpicLabel引用,因此调用

picLabel.setIcon(image); 

应该设置的图标现有JLabel

1

必须调用

picLabel.setIcon(image); 
0

保持到picLabel参考你的类和动作监听通话picLabel.setIcon(new ImageIcon("Whatever.jpg"));改变图片。