//用匿名类实现关闭窗口功能import java.awt.*;import java.awt.event.*;public class TestAnony { Frame f = new Frame("Test"); TextField tf = new TextField(10); Button b1 = new Button("Start"); public TestAnony() { f.add(b1, BorderLayout.NORTH); f.add(tf, BorderLayout.SOUTH); b1.addActionListener(new ActionListener() { private int i; public void actionPerformed(ActionEvent e) { tf.setText(e.getActionCommand() + ++i); } }); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { f.setVisible(false); System.exit(0); } }); f.pack(); f.setVisible(true); } public static void main(String[] args) { new TestAnony(); }}
//简单的画图程序//注意repaint()方法的使用import java.awt.*;import java.awt.event.*;import java.util.*;public class TestMyMouseAdater { public static void main(String[] args) { new MyFrame("Drawing ......"); }}class MyFrame extends Frame { ArrayList points = null; MyFrame(String s) { super(s); points = new ArrayList (); setLayout(null); setBounds(300, 300, 400, 400); setBackground(new Color(204, 204, 255)); setVisible(true); this.addMouseListener(new Monitor()); //this.addWindowListener(new MyWindowMonitor()); //匿名类写法: this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { setVisible(true); System.exit(0); } }); } //内部类 /*class MyWindowMonitor extends WindowAdapter { public void windowClosing(WindowEvent e) { setVisible(false); System.exit(0); } }*/ public void paint(Graphics g) { Iterator i = points.iterator(); while(i.hasNext()) { Point p = i.next(); g.setColor(Color.blue); g.fillOval(p.x, p.y, 10, 10); } } public void addPoint(Point p) { points.add(p); }}class Monitor extends MouseAdapter { public void mousePressed(MouseEvent e) { MyFrame f = (MyFrame)e.getSource(); f.addPoint(new Point(e.getX(), e.getY())); f.repaint(); }}