Java JButton中的图像不显示
有人能看一下这个代码并告诉我我做错了什么吗?根本不显示图像。它们在同一个包裹里 谢谢Java JButton中的图像不显示,java,swing,package,imageicon,Java,Swing,Package,Imageicon,有人能看一下这个代码并告诉我我做错了什么吗?根本不显示图像。它们在同一个包裹里 谢谢 public class MWindow31Pic extends JFrame implements ActionListener{ private JPanel contPane = (JPanel) this.getContentPane(); private JButton button = new JButton(new ImageIcon("open.jpg"))
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);
}
}
您应该像这样创建ImageIcon:
new ImageIcon ( MWindow31Pic.class.getResource ( "close.jpg" ) )
因为以你的方式:
new ImageIcon ( "close.jpg" )
映像应该在应用程序工作目录中,但不在调用类包中
您可能还希望将图像移动到单独的文件夹中:
new ImageIcon ( MWindow31Pic.class.getResource ( "images/close.jpg" ) )
它获取图像文件的本地URL,该文件包含在您的jar中(或者在类尚未打包的情况下包含在外部)。只需尝试将该URL作为字符串输出,并查看它为您提供了什么,例如:System.out.println(MWindow31Pic.class.getResource(“close.jpg”);