Java uses the same event listener for the same type of component

description

  • Java USES the same event listener for the same type of component to simplify the program and avoid writing duplicate code.
  • distinguishes different components by setting the name.

program code

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TextEve2 {

	public static void main(String[] args) {
		JFrame jf=new JFrame("test event");
		//创建多个同类型的事件源
		TextField tf1=new TextField(30);
		tf1.setName("tf1");
		TextField tf2=new TextField(30);
		tf2.setName("tf2");
		//注册事件监听器
		tf1.addTextListener(new MyTextListener());
		tf2.addTextListener(new MyTextListener());

		//添加组件
		Component strut = Box.createVerticalStrut(5);
		Box vBox = Box.createVerticalBox();
		vBox.add(tf1);
		vBox.add(strut);
		vBox.add(tf2);
		JPanel panel=new JPanel(new FlowLayout(FlowLayout.LEFT,5,10));
		panel.add(vBox);
		jf.add(panel);
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jf.pack();
		jf.setVisible(true);
	}

	//自定义事件监听器
	private static class MyTextListener implements TextListener{
		@Override
		public void textValueChanged(TextEvent e) {
			TextField tf = (TextField) e.getSource();
			//根据不同事件源,执行不同的逻辑
			String name = tf.getName();
			switch (name){
				case "tf1":
					System.out.println("文本1内容= "+tf.getText());
					break;
				case "tf2":
					System.out.println("文本2内容= "+tf.getText());
					break;
				default:
					break;
			}
		}
	}
}


Read More: