如何设置
JFrame
的背景颜色?获取框架的内容面板,使用从Component继承的setBackground()方法更改颜色。
例如:
myJFrame.getContentPane().setBackground( desiredColor );
设置JFrame的背景颜色:
getContentPane().setBackground(Color.YELLOW); //Whatever color
使用:
setBackground(Color.red);
无法正常工作。
使用
Container c = JFrame.getContentPane();
c.setBackground(Color.red);
或者myJFrame.getContentPane().setBackground( Color.red );
getContentPane().setBackground(new java.awt.Color(204, 166, 166));
这是一个RGB颜色示例,你可以用你想要的颜色替换它。如果你不知道RGB颜色代码,请在互联网上搜索...有很多提供自定义颜色的网站。
要为JFrame设置背景色,请尝试以下方法:
this.getContentPane().setBackground(Color.white);
你好,我曾经遇到过同样的问题,在多次尝试后,我发现问题在于需要一个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));
}
}
Container c = JFrame.getContentPane();
c.setBackground(Color.red);
当然,您需要导入 java.awt.Color
以使用红色的常量。
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()
的类等效方法。
你可以重写JFrame的paint方法,然后使用你喜欢的颜色填充它,像这样:
@Override
public void paint(Graphics g) {
g.setColor(Color.red);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
}
我也遇到了更改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);
}