简体   繁体   English

除非我调整JFrame的大小,否则图像不会出现

[英]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 我一直在尝试使用JPanel在JFrame上显示图像,但是该图像仅在我调整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. Toolkit.createImage()异步加载图像。 Try specifying image observer. 尝试指定图像观察器。 JPanel implements ImageObserver so can use the following line: JPanel实现ImageObserver因此可以使用以下行:

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

As an alternative, you can use ImageIO.read which load images synchronously. 或者,您可以使用ImageIO.read来同步加载图像。

According to the JFrame Tutorial they recommend doing either pack or setSize just before you set visible. 根据JFrame教程,他们建议在设置visible之前执行pack或setSize。 How about changing the order of add and setSize? 如何更改add和setSize的顺序?

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

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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