2016-08-23 18 views
1

スイングでの背景の色を変更することはできません。それは私がちょうど回っていた本当に簡単なポンゲームですが、私は背景の色を変更することはできません。 「あなたは赤にするのJFrameの背景を設定している背景スイングの色を変更することはできません

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

     } 
    } 
} 
+1

に。 'frame.getContentPane()。setBackground(..)'の代わりに 'game.setBackground(Color.red);を試してください。 – ArcticLord

答えて

1

、しかしあなた:ここに私のコードは、[背景色をメインに変更される]である(私はそれが厄介だけど、私はまだ学んでいます)それをカバーするJPanelが追加されました。

あなたは変更することでこの問題を解決することができます:あなた `Pong`クラスを使用すると、` game`オブジェクトの背景を変更する必要があり `JPanel`あるので

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

game.setBackground(Color.red); 
+0

これはうまくいかず、単にゲームの下線を引いて、 'シンボルを見つけることができません'と言います。私は正しい場所にその行を挿入していますか? – Cutter

+1

それは 'Pong game = new Pong();'という行を置く必要があるからです。 – ArcticLord

+0

'Pong game = new Pong();'と 'frame.add(game);'の間で行う必要があります。その後、それは動作します。 – byxor

関連する問題