希望这不是一个重复的帖子,但我真的找不到解决方案。
所以,我想把一张图片放到所有面板上
这是我的代码:
public class MyFrame extends JFrame{
private BufferedImage backgroundImage;
public MyFrame() throws IOException {
setSize(650, 450);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Dragon Game");
setResizable(false);
getContentPane().setFocusTraversalPolicyProvider(true);
getContentPane().setBounds(new Rectangle(0, 0, 650, 450));
getContentPane().setSize(650,450);
getContentPane().setLayout(null);
JPanel gamePanel = new JPanel();
gamePanel.setBounds(0, 25, 650, 375);
getContentPane().add(gamePanel);
gamePanel.setLayout(null);
try{
backgroundImage = ImageIO.read( new File("imgs/dragon.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
protected void paintComponent(Graphics g){
requestFocus(true);
setFocusable(true);
g.drawImage(backgroundImage, 0, 0, this.getWidth(), this.getHeight(), Color.WHITE, null);
}
}
任何想法?