Images in JButton do not display

Can someone please take a look at this code and tell me what am I doing wrong? Images are not displayed at all. They are in one package.

thanks

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
source share
1 answer

You must create ImageIcon as follows:

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

Because in his own way:

 new ImageIcon ( "close.jpg" ) 

the image must be inside the working directory of the application, but not inside the package of the calling class.

You can also move images to a separate folder:

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

All Articles