公司网站建设成都,网站电子商务类型,企业网站建设门户,阅读分享网站模板介绍#xff1a;
ActionListener是一个接口#xff0c;ActionEvent通常在点击一个按钮或双击某个列表项或选中某个菜单时发生。
如何设置监听#xff1a;
对监听者添加ActionListener接口#xff0c;实现其所有方法#xff0c;重写需要用到的方法对事件进行处理#x…介绍
ActionListener是一个接口ActionEvent通常在点击一个按钮或双击某个列表项或选中某个菜单时发生。
如何设置监听
对监听者添加ActionListener接口实现其所有方法重写需要用到的方法对事件进行处理最后对事件源注册监听。
代码实现
确定事件源和监听者 —确定事件类型 — 实现该类型接口 — 事件处理方法重写接口方法— 事件源注册监听事件源添加监听者
写一个程序带四个按钮和一个多行文本框按下按钮能在文本框内显示按钮名称。 界面分析以按钮为事件源以界面为监听者因为与按钮点击有关用ActionListener接口重写其方法注册监听。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ActionEvent_1 extends JFrame implements ActionListener{JPanel jp1;JButton jb1,jb2,jb3,jb4;JTextArea jta1;public static void main(String[] args) {ActionEvent_1 anew ActionEvent_1();}ActionEvent_1(){jp1new JPanel();jb1new JButton(W);jb1.addActionListener(this);jb2new JButton(A);jb2.addActionListener(this);jb3new JButton(S);jb3.addActionListener(this);jb4new JButton(D);jb4.addActionListener(this);jta1new JTextArea();jp1.add(jb1);jp1.add(jb2);jp1.add(jb3);jp1.add(jb4);this.add(jp1,BorderLayout.NORTH);this.add(jta1);this.setTitle(我的小程序);this.setSize(400, 300);this.setLocation(100, 100);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);}Overridepublic void actionPerformed(ActionEvent e) {if(e.getSource()jb1)jta1.setText(W);else if(e.getSource()jb2)jta1.setText(A);else if(e.getSource()jb3)jta1.setText(S);else if(e.getSource()jb4)jta1.setText(D); }
}
操作方法
事件源四个按钮。
监听者面板。
处理方法在文本域中设置文本。