一般我们要生成一个窗口,通常是用Window的子类Frame来进行实例化,而不是直接用到Window类。Frame的外观就像我们平常在windows系统下见到的窗口,有标题、边框、菜单、大小等等。每个Frame的对象实例化以后,都是没有大小和不可见的,因此必须调用setSize( )来设置大小,调用setVisible(true)来设置该窗口为可见的。
另外,AWT在实际的运行过程中是调用所在平台的图形系统,因此同样一段AWT程序在不同的操作系统平台下运行所看到的图形系统是不一样的。例如在windows下运行,则显示的窗口是windows风格的窗口;而在UNIX下运行时,则显示的是UNIX风格的窗口。
例1:不带panel的框架窗口
package myawt;
import java.awt.*;
public class MyFrame extends Frame
{
private static final long serialVersionUID = 1L;
public MyFrame(String string)
{
super(string);//调用父类的构造方法
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
MyFrame fr = new MyFrame("hello");
fr.setSize(250, 250);
fr.setBackground(Color.blue);
fr.setVisible(true);
}
}
例2:带panel的窗口框架
package myawt;
import java.awt.*;
public class FrameWithPanel extends Frame
{
public FrameWithPanel(String str)
{
super(str);
}
public static void main(String[] args)
{
FrameWithPanel fr = new FrameWithPanel("Frame with Panel");
Panel pan = new Panel();
fr.setSize(200, 200);
fr.setBackground(Color.red); // 框架的背景颜色设置为红色
fr.setLayout(null); //取消布局管理
pan.setSize(100, 100); //pan的大小设置
pan.setBackground(Color.yellow);//pan的背景设置为黄色
fr.add(pan); // 用add方法把面板pan添加到框架中
fr.setVisible(true);
}
}