import javax.swing.*;
import java.awt.*;public class ppp {
public static void main(String[] args) {
JFrame frame=new JFrame("hello swing");
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
frame.setSize(300,100);
frame.setBackground(Color.red);
frame.setVisible(true);
}}
import java.awt.*;public class ppp {
public static void main(String[] args) {
JFrame frame=new JFrame("hello swing");
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
frame.setSize(300,100);
frame.setBackground(Color.red);
frame.setVisible(true);
}}
JPanel p = new JPanel();
p.setBackground(Color.red);
frame.add(p);
import java.awt.*; public class ppp extends JFrame{
ppp(){
setSize(300,100);
getContentPane().setBackground(Color.red);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); }
public static void main(String[] args) {
new ppp();
} }
你就是查到有这个方法,也是不对的。JFrame 包含了好几个Panel.
我们在屏幕上看到是contantPanel,所以应该给contantpanel加背景色。
JFrame框架,一旦创建,在其中就已经包含一个内容面板,一般我们在往JFrame中添加组件时,都加在了内容面板中,这个面板可以通过JFrame的成员方法getContentPane()取出来,
所以如果设置JFrame的背景颜色,仍然会被内容面板盖住,不如设置内容面板的背景颜色
当时如果框架中还加有其他面板,内容面板的颜色也会被其他面板盖住,要注意一下面板的布局情况你可以试验下,尝试frame.getContentPane().setVisible(false);将面板隐藏,那么就可以设置JFrame的背景颜色也就显示出来了。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame; public class ddd extends JFrame { /**
* Launch the application
* @param args
*/
public static void main(String args[]) {
try {
ddd frame = new ddd();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the frame
*/
public ddd() {
super();
getContentPane().setBackground(Color.red);
getContentPane().setLayout(null);
setBounds(100, 100, 500, 375);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JButton clickButton = new JButton();
clickButton.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Color c=new Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256));
getContentPane().setBackground(c);
}
});
clickButton.setText("click");
clickButton.setBounds(173, 53, 106, 28);
getContentPane().add(clickButton);
}
}