2012-08-17 71 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