我无法改变挥杆背景的颜色。这是一个非常简单的乒乓球比赛,我只是搞乱但我无法改变背景颜色。这是我的代码[背景颜色在主要部分改变](我知道它很乱,我还在学习):
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);
}
}
}
答案 0 :(得分:1)
您已将 JFrame的背景设置为红色,但您已添加了覆盖它的JPanel。
您可以通过更改以下内容来解决此问题:
frame.getContentPane().setBackground(Color.red);
到
game.setBackground(Color.red);