我的代码
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Flappy bird");
frame.setSize(1200, 800);
FlappyBird game = new FlappyBird();
frame.getContentPane().setBackground(Color.YELLOW);
frame.add(game);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
while (true) {
game.moveBall();
game.gameOver();
game.moveRect();
game.repaint();
Thread.sleep(14);
}
}
为什么frame.getContentPane().setBackground(Color.YELLOW);
不起作用?
我尝试重新排列顺序,例如在使框架可见后设置颜色。
最佳答案
它工作正常,但您看不到背景颜色,因为您的 FlappyBird
实例绘制在它的上面。您可以通过用空 Canvas 替换游戏类来轻松验证这一点,如下所示:
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Flappy bird");
frame.setSize(1200, 800);
//FlappyBird game = new FlappyBird();
Canvas game = new Canvas();
frame.getContentPane().setBackground(Color.YELLOW);
frame.add(game);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
// while (true) {
// game.moveBall();
// game.gameOver();
// game.moveRect();
// game.repaint();
// Thread.sleep(14);
// }
}
您可以尝试以下两件事:
- 设置
游戏
而不是框架内容 Pane 的背景颜色:
//frame.getContentPane().setBackground(Color.YELLOW);
game.setBackground(Color.YELLOW);
- 通过将游戏实例设为透明来确保框架的背景颜色透过游戏实例显示:
game.setOpaque(false);
关于java - JFrame 背景颜色不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40661901/