2014-04-04 105 views
1

我知道這已被回答了幾次,但我發現的那些回答了程序特定的代碼塊,我無法辨別具體代碼實際上是否改變了圖像。我試圖在運行時通過按下按鈕來更改我的GUI上的jlabel圖像。如何更改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

請書籤的http://文檔.oracle.com/JavaSE的/ 7 /文檔/ API /。如果你搜索,你會找到解釋。 – Axel

回答

2

您正在尋找JLabel'ssetIcon方法

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

你試過嗎?

//代碼我需要改變圖像 呼叫已定義JLabel中的功能,並通過例如映像位置:images/image.png

yourfunction(String imagelocation) 
{ 

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

} 

參考:http://docs.oracle.com/javase/7/docs/api/