当前位置:编程学习 > JAVA >>

java例程练习(匿名类用法)

//用匿名类实现关闭窗口功能 
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(); 
    } 

[java]
//简单的画图程序 
//注意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<Point> points = null; 
    MyFrame(String s) { 
        super(s); 
        points = new ArrayList<Point>(); 
        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<Point> 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(); 
    } 

 

 

摘自 Yours风之恋

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,