W. Emanuel W. Emanuel - 20 days ago 6
Java Question

JFrame background color not working

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.

Answer

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:

  1. Setting the background color not of the frame's content pane but of game:
//frame.getContentPane().setBackground(Color.YELLOW);
game.setBackground(Color.YELLOW);
  1. Making sure that the frame's background color shows through the game instance by making the latter transparent:
game.setOpaque(false);