我一直在尝试使用 JPanel 在 JFrame 上显示图像,但只有在调整 JFrame 大小时才会显示图像
展示:
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);
}
}
飞船
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);
}
}
我知道发生了什么,所以我得到的任何帮助将不胜感激