为JFrame设置背景颜色

69
如何设置 JFrame 的背景颜色?
14个回答

90

获取框架的内容面板,使用从Component继承的setBackground()方法更改颜色。

例如:

myJFrame.getContentPane().setBackground( desiredColor );

38

设置JFrame的背景颜色:

getContentPane().setBackground(Color.YELLOW);  //Whatever color

13

使用:

setBackground(Color.red);

无法正常工作。

使用

Container c = JFrame.getContentPane();

c.setBackground(Color.red);
或者
myJFrame.getContentPane().setBackground( Color.red );

5
如果其他用户已经给出了相同的答案,为什么还需要回答? - Filipe Brito
他的第一句话很有道理,即setBackGround无法正常工作。 - crackerplace

6
这是最简单和正确的方法。您只需在initComponents()之后添加此代码即可。
getContentPane().setBackground(new java.awt.Color(204, 166, 166));

这是一个RGB颜色示例,你可以用你想要的颜色替换它。如果你不知道RGB颜色代码,请在互联网上搜索...有很多提供自定义颜色的网站。


6

要为JFrame设置背景色,请尝试以下方法:

this.getContentPane().setBackground(Color.white);

我认为这是一个可能是答案的解决方案建议。如果楼主尝试并发现它有效,他们可以要求您将其添加为答案并标记它。这通常是我的工作方式。 - midhunhk
感谢您提供这个好的解决方案。看起来“Color”中的“C”是大小写敏感的。 - Ahm23

3

你好,我曾经遇到过同样的问题,在多次尝试后,我发现问题在于需要一个Graphics对象才能绘制和设置背景颜色。

我的代码通常是这样的:

import javax.swing.*;
import java.awt.*;


public class DrawGraphics extends JFrame{

    public DrawGraphics(String title) throws HeadlessException {
      super(title);
      InitialElements();
    }

    private void InitialElements(){
      setSize(300, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
      // This one does not work
      // getContentPane().setBackground(new Color(70, 80, 70));

    }

    public void paint(Graphics draw){
      //Here you can perform any drawing like an oval...
      draw.fillOval(40, 40, 60, 50);

      getContentPane().setBackground(new Color(70,80,70));
    }
}

几乎所有其他答案都没有提到代码应该放在哪里。现在你知道它应该放在paint(Graphics G)中。

我们__绝不能__在绘制过程中更改组件的状态。尽管它更改了子级的状态,这也是不允许的,因为其工作与否取决于实现细节(例如,在更改子级状态之前/之后调用super.paint - 这是强制性的,但在此处缺失..为简洁起见我假设)。无关的小问题:在公开显示Java代码时,请遵循Java命名约定。 - kleopatra

2
你可以使用一个容器,如下所示:
Container c = JFrame.getContentPane();
c.setBackground(Color.red); 

当然,您需要导入 java.awt.Color 以使用红色的常量。


2
这里是另一种方法:
private void RenkMouseClicked(java.awt.event.MouseEvent evt) {
    renk = JColorChooser.showDialog(null, "Select the background color",
            renk);
    Container a = this.getContentPane();
    a.setBackground(renk);
}

我正在使用NetBeans集成开发环境。对我来说,JFrame.getContentPane()没有执行。我使用了this.getContentPane作为JFrame.getContentPane()的类等效方法。


1

你可以重写JFrame的paint方法,然后使用你喜欢的颜色填充它,像这样:

@Override
public void paint(Graphics g) {
    g.setColor(Color.red);
    g.fillRect(0, 0, this.getWidth(), this.getHeight());
}

1

我也遇到了更改JFrame背景的问题,上述回答并没有完全解决。我正在使用Eclipse。添加布局解决了这个问题。

public class SampleProgram extends JFrame {
    public SampleProgram() {
        setSize(400,400);
        setTitle("Sample");
        getContentPane().setLayout(new FlowLayout());//specify a layout manager
        getContentPane().setBackground(Color.red);
        setVisible(true);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接