简体   繁体   中英

Image won't appear on JFrame

This is my code:

    import java.awt.BorderLayout;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;

    public class SenzuView extends JFrame {
      JLabel label;
      public SenzuView(){
        ImageIcon image = new ImageIcon("C:\\senzu.jpg");
        label = new JLabel("", image, JLabel.CENTER);
        this.add(label);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setExtendedState(JFrame.MAXIMIZED_BOTH);
        this.setVisible(true);
    }
    public static void main(String[] args) {
        new SenzuView();
    }
}    

The problem is that the Frame opens but its empty and the image never appears Thanks in advance

I suggest you use the getClass.getResource because that way if you later wants to compile the project into a .jar file the images will come with the project or else they wont appear if you go along with the solution path you were originally starting on.

  • Make a folder inside your package where your main class is located in. Preferably called 'res'
  • Move your image to that package.
  • Initialize the image icon like this:

     ImageIcon image = new ImageIcon(getClass().getResource("res/senzu.jpg"))
  • The following is an example of how I suggest you should have your SenzuView coded:

     public SenzuView(){ setLayout(new BorderLayout()); ImageIcon image = new ImageIcon(getClass().getResource("res/senzu.jpg")); label = new JLabel(image); this.add(label, BorderLayout.CENTER); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLocationRelativeTo(null); setExtendedState(JFrame.MAXIMIZED_BOTH); setVisible(true) }

I hope this solved it and gave you some other useful tips.

I suggest you to create a folder in your project directory named images . Then give the path as this:

ImageIcon image = new ImageIcon("images/senzu.jpg");

This will work.

If you need an absolute path then use

C:/Program Files/workspace/Senzu/images/senzu.jpg

Hope it solved your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM