JButton中的图片未显示

4

请有人帮忙看一下这段代码,告诉我哪里出了问题?图片根本没有显示出来。图片和代码在同一个包中。

谢谢

    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);
    }
   }
1个回答

4

您应该按照以下方式创建ImageIcon:

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

因为使用您的方法:
new ImageIcon ( "close.jpg" )

图像应该位于应用程序工作目录内,但不应位于调用类包内。

您可能还想将图像移动到一个单独的文件夹中:

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

它获取包含在您的jar文件中(或在类尚未打包的情况下位于外部)的图像文件的本地URL。只需尝试将该URL作为字符串输出并查看它给您的结果,例如:System.out.println(MWindow31Pic.class.getResource("close.jpg")); - Mikle Garin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接