{相关信息}
当一个内部类只创建一个对象,并且该类继承一个父类或者实现一个接口的时候,才考虑使用匿名类。
{代码实现}
package sup.orange.learn; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; /** * Created by re-x on 11/2/14. */ public class ListenerAnonymouseClass { private Frame f; private TextField tf; public ListenerAnonymouseClass() { f = new Frame("click or move"); tf = new TextField(30); } public static void main(String[] args) { ListenerAnonymouseClass la = new ListenerAnonymouseClass(); la.show(); } public void show() { f.add("North", tf); f.setSize(200, 300); f.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); f.dispose(); f.setVisible(false); System.exit(0); } }); f.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { super.mouseMoved(e); tf.setText("x="+e.getX()+",y="+e.getY()); } }); f.setVisible(true); } }
时间: 2024-10-29 10:46:14