Database Development Week Learning (II) java in swing (event listener)

I. Basic Concepts

1. The event indicates that the interaction between the program and the user, for example in the text box, select the list box or combo box, select the check boxes and radio buttons, click a button and so on.
2. During the event processing, mainly related to three types of objects.

• Event (event): Users on one operation component called an event, in the form of classes. For example, an event type corresponding to the keyboard is KeyEvent.
• Event Source (Event Source): places events, usually the individual components, such as buttons Button.
• Event Handler (event handler): receive the event object and its object event processor for processing, is usually a member of the Java class method is responsible for handling the event.

3. The event handler (listeners) is generally a class if they can handle certain types of events, it is necessary to implement the event type opposite to the interface. For example, a class has been able to handle ButtonHandler ActionEvent event, because it implements the interface corresponding to the event ActionListener and ActionEvent. Each event has a class with the corresponding interface.

Code

package cn.edu.hbue.wmp;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

//1.implements继承接口抽象类
public class JFrameDemo07 extends JFrame implements ActionListener{

	
	JLabel j;
	JButton btn1;
	JButton btn2;
	JButton btn3;
	JButton btn4;
	JTextField jf;
	
	public JFrameDemo07(){
		
		
		//窗口属性
		setTitle("多事件源");
		setSize(400,200);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		
		j = new JLabel("请输入文字");
		btn1 = new JButton("1");
		btn2 = new JButton("2");
		btn3 = new JButton("3");
		btn4 = new JButton("4");
		jf = new JTextField(10);
		
		
		Container c = getContentPane();
		c.setLayout(new FlowLayout());
		
		//2.添加监听器件
		btn1.addActionListener(this);
		btn2.addActionListener(this);
		btn3.addActionListener(this);
		btn4.addActionListener(this);
		
		c.add(j);
		c.add(btn1);
		c.add(btn2);
		c.add(btn3);
		c.add(btn4);
		c.add(jf);
		
		setVisible(true);
		
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		new JFrameDemo07();
	}
	
	//设置相应消息响应函数
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		
		StringBuffer str = new StringBuffer(jf.getText());
		str.append(e.getActionCommand());
		String str1 = new String(str);
	
		jf.setText(str1);
	}
	
	

}

Published 21 original articles · won praise 16 · views 2857

Guess you like

Origin blog.csdn.net/fjd7474/article/details/104582775