My code
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);
}
}
Why isn't the frame.getContentPane().setBackground(Color.YELLOW);
working?
I've tried to rearrange the order, like setting the color after making the frame visible.
It works alright, but you cannot see the background color because your FlappyBird
instance is drawn on top of it. You can easily verify this by replacing your game class with an empty canvas like so:
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);
// }
}
There are two things you can try:
game
: //frame.getContentPane().setBackground(Color.YELLOW);
game.setBackground(Color.YELLOW);
game.setOpaque(false);
Removing the lines related to game, I was able to run this with the expected yellow result. The issue must be within the while loop
while (true) {
game.moveBall();
game.gameOver();
game.moveRect();
game.repaint();
Thread.sleep(14);
}
or
frame.add(game);
Without the FlappyBird class it's impossible to say exactly what is causing the issue, but based on the method names I'd look at repaint().
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.