[英]Images within JButton not displayed
有人可以看看這段代碼並告訴我我做錯了什么? 根本沒有顯示圖像。 它們在同一個包裝中。
謝謝
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" )
image應位於應用程序工作目錄內,但不在調用類包內。
您可能還想將圖像移動到單獨的文件夾中:
new ImageIcon ( MWindow31Pic.class.getResource ( "images/close.jpg" ) )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.