如何使用Java AWT setBackground

ACa*_*ter 3 java user-interface swing awt colors

这是创建基本java窗口的一些代码:

JPanel pane = new JPanel();
gui(String title){
    super(title);
    setBounds(100,100,500,500);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container con = this.getContentPane();
*   con.setBackground(new Color(0,0,0));
    con.add(pane);
    setVisible(true);
}
Run Code Online (Sandbox Code Playgroud)

标有星号(*)的行旨在使窗口的背景颜色变为黑色(0,0,0).但是,这条线似乎无能为力.(我试过pane.setBackground在这里使用,但没有任何差异.)

如何更改背景颜色?

Rei*_*eus 5

您添加JPanelJFrame完全阻止您已设置颜色的基础容器.

你可以这样做:

public Gui(String title) {
   super(title);
   JPanel pane = new JPanel();
   setBounds(100, 100, 500, 500);
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Container con = this.getContentPane();
   pane.setBackground(new Color(0, 0, 0));
   con.add(pane);
   setVisible(true);
}
Run Code Online (Sandbox Code Playgroud)