java设置窗口颜色设置颜色设置颜色_java窗口背景颜色怎么设定?用setBackground()好像不行,请大侠指教!...

展开全部

你好!

首先,你62616964757a686964616fe4b893e5b19e31333264636163说的Java窗口是指JFrame或者Frame

其次,你说的窗口背景颜色是指直接调用JFrame或者Frame的setBackground(Color color)方法设置后显示出来的颜色。其实,你的想法是正确的,但是我想提醒你的是,你没搞明白JFrame的显示机制。在你直接调用这个方法后,你的确设置了背景颜色,而你看到的却不是直接的JFrame或者Frame,而是JFrame.getContentPane().而JFrame上的contentPane默认是Color.WHITE的,所以,无论你对JFrame或者Frame怎么设置背景颜色,你看到的都只是contentPane.

最后,讲解决办法:

办法A:在完成初始化,调用getContentPane()方法得到一个contentPane容器,然后将其设置为不可见,即setVisible(false)。这样,你就可以看到JFrame的庐山真面貌啦!

核心代码this.getContentPane().setVisible(false);//得到contentPane容器,设置为不可见

实例完整代码如下:

/*

* TestJFrameBGColor.java

*

* Created on 2011-5-8, 0:21:20

*/

package testjframebgcolor;

import java.awt.Color;

/**

*

* @author 叶科良

*/

public class TestJFrameBGColor extends javax.swing.JFrame {

/** Creates new form TestJFrameBGColor */

public TestJFrameBGColor() {

initComponents();

this.getContentPane().setVisible(false);//得到contentPane容器,设置为不可见

}

/** This method is called from within the constructor to

* initialize the form.

* WARNING: Do NOT modify this code. The content of this method is

* always regenerated by the Form Editor.

*/

@SuppressWarnings("unchecked")

// 

private void initComponents() {

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(testjframebgcolor.TestJFrameBGColorApp.class).getContext().getResourceMap(TestJFrameBGColor.class);

setBackground(resourceMap.getColor("Form.background")); // NOI18N

setName("Form"); // NOI18N

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGap(0, 400, Short.MAX_VALUE)

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGap(0, 300, Short.MAX_VALUE)

);

pack();

}// 

/**

* @param args the command line arguments

*/

public static void main(String args[]) {

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new TestJFrameBGColor().setVisible(true);

}

});

}

// Variables declaration - do not modify

// End of variables declaration

}

方法B:将contentPane的颜色设置为你想要的颜色,而不是对JFrame本身设置,

核心代码:this.getContentPane().setBackground(Color.red);//设置contentPane为红色

将核心代码替换方法A核心代码即可实现

方法C:为JFrame添加一个Panel或者JLabel等其他组件,设置其颜色为你想要的颜色,然后将其覆盖JFrame窗口即可

975af5a4cf17ac030a503c77174ccafe.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值