监视器代码
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Main{ public static void main(String[] args) { Window win=new Window(); } }class Window extends JFrame{ ActionListener listener; JTextField text; public Window(){//构造方法 setBounds(150,150,300,100); text=new JTextField(10); add(text);//把text这个组件加到窗口这个容器上 listener=new ReaderListener();//搞一个监视器(接口回调) text.addActionListener(listener);//把监视器绑定到text上 setVisible(true);// setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// setLayout(new FlowLayout());//注意:第21、22、23行必须有一行在最后,要不执行完属于win的方法之后构造方法就不执行其他的了
}
}
class ReaderListener implements ActionListener{ //ActionListener是一个接口,别当成类了
@Override
public void actionPerformed(ActionEvent e) {
String str=new String(e.getActionCommand());
System.out.println(str+":"+str.length());
}
}
//这是书上的源码,上面是自己编的;
import java.awt.*;
import java.awt.event.*;
import java.io.Reader;
import javax.swing.*;
public class Main{
public static void main(String[] args) {
WindowActionEvent win=new WindowActionEvent();
win.setBounds(100,100,310,260);
}
}
class WindowActionEvent extends JFrame{
JTextField text;
ActionListener listener;
public WindowActionEvent(){
setLayout(new FlowLayout());
text=new JTextField();
this.add(text);
listener=new ReaderListener();
text.addActionListener(listener);//addxxxListener
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class ReaderListener implements ActionListener{
public void actionPerformed(ActionEvent e){//这个事件就是text,因为19行有this.add(text);
String str=e.getActionCommand();
System.out.println(str+":"+str.length());
}
}
本文来自博客园,作者:{李浩正},转载请注明原文链接:https://www.cnblogs.com/hzzzz/p/16282575.html