Search code examples
javaswingpackageimageicon

Images within JButton not displayed


Can someone please have a look at this code and tell me what am I doing wrong? The images are not being displayed at all. They are in the same 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);
    }
   }

Solution

  • You should create ImageIcon like this:

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

    Because with your way:

    new ImageIcon ( "close.jpg" )
    

    image should be inside the application working directory but not inside the calling class package.

    You might also want to move images into a separate folder:

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