Cutter Cutter - 3 months ago 6
Java Question

can't change colour of background swing

I can't change the colour of my background in swing. It is a really simple pong game I was just messing around with but I can't change the background colour. Here is my code [the background colour is changed in the main](I know it's messy, I'm still learning):

public class Pong extends JPanel {
int x = 0;
int y = 000;
int yP = 300;
int xP = 300;

int border = 50;
boolean ballGoingDown = true;
boolean ballGoingRight = true;

private void moveBall() throws InterruptedException {
if (ballGoingRight == true) {
x++;
}

if (ballGoingRight == false) {
x--;
}


if (ballGoingDown == true) {
y++;
}

if (ballGoingDown == false) {
y--;
}

if (y == getHeight() - border) {
ballGoingDown = false;
}

if (y == 0) {
ballGoingDown = true;
}

if (x == getWidth() - border) {
ballGoingRight = false;
}

if (x == 0) {
ballGoingRight = true;
}
}


@
Override
public void paint(Graphics G) {
super.paint(G);
G.fillOval(x, y, 50, 50);
}

public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Pong");
frame.setSize(700, 500);

frame.setVisible(true);
frame.getContentPane().setBackground(Color.red);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Pong game = new Pong();
frame.add(game);

while (true) {
game.repaint();
game.moveBall();
Thread.sleep(1);

}
}
}

Answer

You're setting the JFrame's background to be red, but you've added a JPanel which covers it.

You can fix this by changing:

frame.getContentPane().setBackground(Color.red);

to

game.setBackground(Color.red);