【问题标题】:can't change colour of background swing不能改变背景摇摆的颜色
【发布时间】:2016-08-23 13:28:09
【问题描述】:

我无法在摇摆中更改背景颜色。这是一个非常简单的乒乓球游戏,我只是在玩弄,但我无法更改背景颜色。下面是我的代码【主里的背景颜色改了】(我知道很乱,还在学习中):

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);

         }
     }
 }

【问题讨论】:

  • 由于您的Pong 类是JPanel,您应该更改game 对象的背景。试试game.setBackground(Color.red); 而不是frame.getContentPane().setBackground(..)

标签: java spring colors background


【解决方案1】:

您将 JFrame 的 背景设置为红色,但您添加了一个覆盖它的 JPanel。

您可以通过更改来解决此问题:

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

game.setBackground(Color.red);

【讨论】:

  • 这不起作用,它只是在游戏下划线并说它“找不到符号”。我是否在正确的位置插入该行?
  • 那是因为你需要把这行放在Pong game = new Pong();下面!!!
  • 您需要在Pong game = new Pong();frame.add(game); 之间进行。然后它会工作。
猜你喜欢
  • 2010-09-17
  • 1970-01-01
  • 1970-01-01
  • 2013-04-29
  • 2023-04-05
  • 2015-06-16
  • 1970-01-01
  • 2012-04-02
相关资源
最近更新 更多