简体   繁体   中英

Image doesn't appear unless I resize JFrame

I have been trying to show a image on an JFrame using a JPanel but the image only shows up if I resize the JFrame

Display:

package display;

import javax.swing.JFrame;
import img.*;

public class Screen extends JFrame{

    private static final long serialVersionUID = 1L;

    Spaceship s = new Spaceship();
    public static void main(String[]args){
    new Screen();
    }

    public Screen(){
    setTitle("Spaceships!");
    setSize(700,605);
    setLocationRelativeTo(null);
    add(s);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);

    }
}

Spaceship

package img;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;

import javax.swing.JPanel;

public class Spaceship extends JPanel{

    private static final long serialVersionUID = 1L;

    Image spaceship = (Image)Toolkit.getDefaultToolkit().getImage(getClass().getResource("res/spaceship.png"));

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawImage(spaceship,100,100,null);
    }
} 

I have know clue whats going on so any help I get would be appreciated

Toolkit.createImage() load images asynchronously. Try specifying image observer. JPanel implements ImageObserver so can use the following line:

g.drawImage(spaceship, 100, 100, this);

As an alternative, you can use ImageIO.read which load images synchronously.

According to the JFrame Tutorial they recommend doing either pack or setSize just before you set visible. How about changing the order of add and setSize?

public Screen(){
    setTitle("Spaceships!");
    setLocationRelativeTo(null);
    add(s);
    setSize(700,605);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);

}

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