0

I am trying to make a main menu and i am now working on the play button. Everything works fine except that it doesn't load an image. The image is in the source folder and this is the code:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;

public class GameFrame extends JFrame implements ActionListener{
    JButton play;
    
    GameFrame() {
        
        ImageIcon icon = new ImageIcon("playButton.png");
        
        play = new JButton();
        play.setBounds(500,100,250,100);
        play.addActionListener(this);
        play.setText("hi");
        play.setFocusable(false);
        play.setIcon(icon);
        
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(null);
        this.setSize(1000,700);
        this.setExtendedState(JFrame.MAXIMIZED_BOTH); 
        this.setUndecorated(false);
        this.setVisible(true);
        this.add(play);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==play) {
            System.out.println("hi");
        }
        
    }

}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Does this answer your question? [How to load icon from resource in Java?](https://stackoverflow.com/questions/8660945/how-to-load-icon-from-resource-in-java) – George Z. Jun 30 '21 at 12:25
  • These answers might help you: https://stackoverflow.com/q/4801386/4476582 – Alex Diamond Jun 30 '21 at 21:03
  • Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An [tag:embedded-resource] must be accessed by URL rather than file. See the [info. page for embedded resource](http://stackoverflow.com/tags/embedded-resource/info) for how to form the URL. – Andrew Thompson Jul 01 '21 at 00:54
  • `this.setVisible(true); this.add(play);` should instead be `this.add(play); this.pack(); this.setVisible(true);`. Setting the GUI visible should be last. After all components are added, but before the GUI is visible, call `pack()` to ensure the GUI is validated and sized to fin the content. The numbers in `this.setSize(1000,700);` are no better than a guess. `this.setLayout(null);` Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. .. – Andrew Thompson Jul 01 '21 at 00:57
  • .. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). `e.getSource()==play` Instead use `e.getSource().equals(play)` more more reliable comparison. – Andrew Thompson Jul 01 '21 at 00:57

0 Answers0