EX2.java
package ex1;
public class EX2 {
public static void main(String args[]){
WindowActionEvent win = new WindowActionEvent();
win.setBounds(100,100,360,360);
win.setTitle("处理ActionEvent事件");
}
}
WindowsActionEvent.java
package ex1;
import java.awt.*;
import javax.swing.*;
public class WindowActionEvent extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
JTextField inputText;
JTextArea textShow;
JButton button;
PoliceListen listener;
public WindowActionEvent(){
init();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void init(){
setLayout(new FlowLayout());
inputText = new JTextField(10);
button = new JButton("读取");
textShow = new JTextArea(10,18);
listener = new PoliceListen();
listener.setJTextField(inputText);
listener.setJTextArea(textShow);
inputText.addActionListener(listener);
button.addActionListener(listener);
add(inputText);
add(button);
add(new JScrollPane(textShow));
}
}
PoliceListen.java
package ex1;
import java.awt.event.*;
import javax.swing.*;
public class PoliceListen implements ActionListener{
JTextField textInput;
JTextArea textShow;
public void setJTextField(JTextField text){
textInput = text;
}
public void setJTextArea(JTextArea area){
textShow = area;
}
public void actionPerformed(ActionEvent e){
String str = textInput.getText();
textShow.append(str+"的长度:"+str.length()+"\n");
}
}
在这个例子中,我们必须掌握三个概念:事件源,监视器,处理事件的接口。