2015-05-14 28 views
1

我試圖設置JFrame框架的背景顏色,但它不工作。 我在這裏錯過了什麼? 這是代碼:setBackgroundColor無法正常工作

public class PingPong extends JPanel{ 

private static final long serialVersionUID = 1L; 
Ball ball = new Ball(this); 
Table table = new Table(this); 
Player player = new Player(this); 
PC pc = new PC(this); 

@Override 
public void paintComponent(Graphics g){ 
    super.paintComponent(g); 

    table.paint(g); 
    ball.repaint(g); 
    player.repaint(g); 
    pc.repaint(g); 

} 

public static void main(String[] args){ 
    /* Creating the frame */ 
    JFrame frame = new JFrame(); 
    frame.setTitle("Ping Pong!"); 
    frame.setSize(600, 600); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.add(new PingPong()); 
    frame.getContentPane().setBackground(Color.DARK_GRAY); 
    frame.setVisible(true); 
} 

}

它只是不會改變顏色..

+0

它實際上工作,只是顏色被PingPong對象覆蓋。 – dragon66

+0

看看這個答案:http://stackoverflow.com/questions/9029367/java-jframe-background-color-not-working似乎是你的問題。 – QueryLars

回答

2

既然你添加JPanel(乒乓對象)到您的JFrameJPanel已超過JFrame,因此JFrame的顏色變得不可見。

setBackground(Color.DARK_GRAY);應用到您的PingPong對象。

+1

謝謝,它正在工作。 –

0

嘗試添加此:

frame.getContentPane().setOpaque(true);