分三种情况来说明:
1. 用户类继承自Frame;
2. Frame对象作为用户类的数据成员;
3. 用户类继承自WindowAdapter.
1. 用户类继承自Frame:
代码如下:
2. Frame对象作为用户类的数据成员:
代码如下:
[java] view plain copy import java.awt.*; import java.awt.event.*; public class MyFrame2{ Frame f = new Frame(); MyFrame2(){ f.addWindowListener(new WindowAdapter(){//为了关闭窗口 public void windowClosing(WindowEvent e){ System.exit(0); } }); }//注意为一个构造函数 public void display(){ f.setTitle("MyFrame"); f.setSize(480,200); f.setLocation (200,400); f.setBackground (Color.lightGray); f.setVisible(true); } public static void main (String args[]) { new MyFrame2().display(); } }3. 用户类继承自WindowAdapter,而窗口对象Frame作为用户类的数据成员.
代码如下:
[java] view plain copy import java.awt.*; import java.awt.event.*; public class MyFrame3 extends WindowAdapter{ Frame f = new Frame(); public void display(){ f.setTitle("MyFrame"); f.setSize(480,200); f.setLocation (200,400); f.setBackground (Color.lightGray); f.addWindowListener (this); //窗体f--注册窗体事件监听器 f.setVisible(true); } public void windowClosing(WindowEvent e){ System.exit(0); } public static void main (String args[]){ new MyFrame3().display(); } }自己的代码:
红色是实现关闭Frame窗口的代码
public class PanelTest1 {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubFrame frame=new Frame("测试程序");frame.setVisible(true);frame.setBounds(30, 30, 300, 300);Panel p=new Panel();p.add(new TextField(30));p.add(new Button("OK"));p.setBackground(Color.yellow);frame.add(p);frame.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e){System.exit(0);}});}}