2015-05-14 32 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);