Java setBackgroundColor不工作

Java setBackgroundColor不工作,java,swing,jpanel,Java,Swing,Jpanel,我正在尝试将JFrame设置为背景色,但它不起作用。 我错过了什么? 代码如下: 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); @Ove

我正在尝试将JFrame设置为背景色,但它不起作用。 我错过了什么? 代码如下:

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

它不会改变颜色。

尝试添加以下内容:

frame.getContentPane().setOpaque(true);

由于将
JPanel
(乒乓球对象)添加到
JFrame
,因此
JPanel
位于
JFrame
上方,因此
JFrame
的颜色变得不可见


应用<代码>立根背景(颜色:深灰色)到你的乒乓球对象。

它实际上是有效的,只是颜色被乒乓球对象覆盖了。看看这个答案:似乎是你的问题。