用JFrame时,设置背景颜色需使用JFrame.getContentPane().setBackground(Color.red)
Container con=this.getContentPane();//得到内容窗格
con.setBackground(Color.blue);
而使用Frame时则可以直接使用setBackground(Color.red),且需要设置窗体默认关闭事件,否则运行窗口无法正常关闭。
将按钮添加到面板,再将面板添加到框架中,要通过面板来调用setBackground()方法来设置框架的背景颜色,直接使用myFrame.setBackground(Color.GREEN);是不会起作用的。原因是JFrame一旦创建,其中已包含一个内容面板,此时myFrame.setBackground无论设置成什么颜色,都将被顶层面板所覆盖。因此,要改变背景颜色,就要改变面板的背景颜色。
import javax.swing.*;
import java.awt.*;
public class win {
public static void main(String args[])
{
JFrame window1=new JFrame("第一个窗口");
JFrame window2=new JFrame("第二个窗口");
Container con=window1.getContentPane();//得到内容窗格
con.setBackground(Color.BLACK);
window1.setBounds(60, 100, 188, 108);
//等价于
//window1.setSize(188,108);
//window1.setLocation(60,100);
window2.setBounds(260, 100, 188, 108);
window1.setVisible(true);//是否可见
window1.setResizable(false);//不可以调整窗口的大小
window1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window2.setVisible(true);
window2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}