初学java之触发响应事件

时间:2023-03-08 21:36:32
 import java.awt.*;
import javax.swing.*;
import java.awt.event.*; class WindowActionEvent extends JFrame
{
JTextField text; //声明一个文本区
ActionListener listener ; //listener是监视器
//设置一个默认的构造函数
public WindowActionEvent()
{
setLayout(new FlowLayout()); //获此容器管理器的布局管理器
text = new JTextField(10); //设置文本区的列行数
add(text); //将这个文本区 添加到文本尾
listener = new ReaderListener(); //创建监视器
text.addActionListener(listener); //注册监视器
setVisible(true); //窗口是否可视化
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
} public class ActionEvent1 {
public static void main(String args[])
{
WindowActionEvent win = new WindowActionEvent();
win.setTitle("处理ActionEvent事件");
win.setBounds(100,100,310,260);
}
}
 import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; public class ReaderListener implements ActionListener { public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String str = e.getActionCommand() ; //获取封装在事件中的“ 命令 ” 字符串
System.out.println(str+":"+str.length());
} }