我尝试将图片添加到JPanel
。
首先,我将图像(.png)拖到项目文件夹中。
然后我输入以下代码,但没有图像出现,只有黑色背景。
GamePanel
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class GamePanel extends JPanel{
private ImageIcon i;
public GamePanel(){
setBackground(Color.BLACK);
setPreferredSize(new Dimension (1080, 720));
i = new ImageIcon("space-ship.png");
}//end constructor
public void paintComponent (Graphics g) {
super.paintComponent (g);
i.paintIcon(this, g, 300, 300);
}
}//end class
game
import java.awt.Dimension;
import javax.swing.JFrame;
public class game {
public static void main(String[] args) {
JFrame frame = new JFrame("space ship game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(1080,720));
frame.add(new GamePanel());
frame.setVisible(true);
frame.pack();
}//end main
}//end class