Java——事件处理机制监听者基础(一)动作监听ActionListener

介绍:

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 a=new ActionEvent_1();
	}
	ActionEvent_1()
	{
		jp1=new JPanel();
		jb1=new JButton("W");
		jb1.addActionListener(this);
		jb2=new JButton("A");
		jb2.addActionListener(this);
		jb3=new JButton("S");
		jb3.addActionListener(this);
		jb4=new JButton("D");
		jb4.addActionListener(this);
		jta1=new 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);
	}
	@Override
	public 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");	
	}
}

操作方法:

事件源:四个按钮。

监听者:面板。

处理方法:在文本域中设置文本。

猜你喜欢

转载自blog.csdn.net/weixin_42247720/article/details/80543348