2012-08-17 52 views
4

有人可以看看這段代碼,並告訴我我做錯了什麼?圖像根本不顯示。他們在同一個包裏。JButton內的圖像不顯示

感謝

public class MWindow31Pic extends JFrame implements ActionListener{ 
     private JPanel contPane = (JPanel) this.getContentPane(); 
     private JButton button = new JButton(new ImageIcon("open.jpg")); 
     boolean clicked = false; 

    public MWindow31Pic(String title){ 
     super(title); 
     this.build(); 
    } 

    public void actionPerformed(ActionEvent event){ 
     if (! clicked) { 
      button.setIcon(new ImageIcon("close.jpg")); 
      //button.setText("You clicked ME!!!!"); 
      clicked = true; 
     } 
     else{ 
      button.setIcon(new ImageIcon("open.jpg")); 
      //button.setText("Click Me"); 
      clicked = false; 
     } 
    } 

    public void build(){ 
     // adding JComponents 
     contPane.add(button); 
     button.addActionListener(this); 

     // JFrame settings  
     this.setResizable(false); 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     this.setLocationRelativeTo(null); 
     this.setSize(240,188); 
     this.setVisible(true); 
    } 
    } 

回答

4

您應該創建ImageIcon的是這樣的:

new ImageIcon (MWindow31Pic.class.getResource ("close.jpg")) 

因爲有你的方式:

new ImageIcon ("close.jpg") 

形象應該是應用程序的工作目錄中不包括其中的調用類包。

您可能還需要將圖像移動到一個單獨的文件夾:

new ImageIcon (MWindow31Pic.class.getResource ("images/close.jpg")) 
+0

它得到的是包含您的罐子裏(或外班的情況下還沒有打包的)圖像文件的本地URL。只要嘗試將該URL輸出爲字符串並查看它給您的內容,例如:System.out.println(MWindow31Pic.class.getResource(「close.jpg」)); – 2012-08-17 10:07:07

+0

瞭解。謝謝 – 2012-08-17 10:09:42