曾经沧海难为水,除却巫山不是云。
事件监听器
-
类要对用户事件作出响应,必须实现处理该事件的接口,这些接口被称为事件监听器。
-
每个监听器都处理特定的事件,类可以根据需要实现任意数目的监听器。
-
监听器模型涉及以下三个对象,模型图如下:
(1)事件:用户对组件的一个操作,称之为一个事件
(2)事件源:发生事件的组件就是事件源
(3)事件监听器(处理器):监听并负责处理事件的方法 -
在java中,事件监听器包含如下接口:
(1)ActionListener:行为事件,由用户对组件执行某种操作(如单击按钮)触发。
(2)AdjustmentListener:调整事件,组件被调整(如移动滚动条上的滑块时)触发。
(3)FocusListener:键盘焦点事件,诸如文本框等组件获得或失去焦点时触发。
(4)ItemListener:选项事件,诸如复选框等选项被修改时激发。
(5)KeyListener:键盘事件,用户通过键盘输入文本时激发。
(6)MouseListener:鼠标事件,鼠标单击,鼠标移入 ,或离开组件时触发。
(7)MouseMotionListener:鼠标移动事件,跟踪鼠标在组件上的运动。
(8)WindowListener:窗口事件,窗口(如应用程序的主窗口)被最大化、最小化、移动或关闭时被触发。 -
执行顺序如下:
1、给事件源注册监听器
2、组件接受外部作用,也就是事件被触发
3、组件产生一个相应的事件对象,并把此对象传递给与之关联的事件处理器
4、事件处理器启动,并执行相关的代码来处理该事件。
给组件注册监听器
创建组件之后,可以通过下面的方法将组件和监听器关联起来。
(1)addActionListener():JButton、JCheck、JComboBox、JTextField、JRadioButton
(2)addAdjustmentListener():JScrollBar组件
(3)addFoucusListener():所有的swing组件
(4)addItemListener():JButton、JCheckBox、JComboBox和JRadioButton组件
(5)addKeyListener():所有的swing组件
(6)addMouseListener():所有的swing组件
(7)addMouseMotionListener():所有的swing组件
(8)addWindowListener():所有的JWindow和JFrame组件。
将组件加入容器之前,必须将组件和监听器关联起来,并完成其他配置操作,否则当程序运行时,这些设置将被忽略。
事件处理方法
- 所有的add方法都接受一个参数:对事件进行监听的对象,This表示当前类就是事件监听器。也可以指定其他的对象,只要它实现了相应的监听器接口。
- 就事件监听器来说,每个方法都是由窗口系统自动调用的,这是在对应的用户事件发生时进行的。
- 如果多个组件有相同的监听器,则必须判断程序中哪个组件被使用了,每种事件处理方法都接受某种事件对象作为参数,这种对象的方法getSource()可用来判断激发事件的组件。
行为事件
- 行为事件在用户使用JButton,JCheckBox,JComboBox,JTextField
JRadioButton.时发生的。 - 要处理这些事件,类必须实现接口ActionListener。此外,必须对每个要激发行为事件的组件调用addActionListener()。
- 方法actionPerformed(Action Event)是接口ActionListener中唯一的方法,其格式为:
public void actionPerformed(ActionEvent evt){
}
行为事件实例
package ActionListenerDemo;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ActionListenerDemo extends JFrame implements ActionListener {
JButton btn1 = new JButton("Rosencrants");
JButton btn2 = new JButton("Guidenstern");
public ActionListenerDemo(){
super("title bar");
setDefaultCloseOperation(EXIT_ON_CLOSE);
btn1.addActionListener(this);
//this指传递的是当前对象,也可传递其他的但必须实现ActionListener接口的对象。
//当事件发生,自动调用传递的参数的actionPerformed()函数。
btn2.addActionListener(this);
//必须先注册监听器事件,再加入容器中,否则会被忽略。
getContentPane().setLayout(new FlowLayout());
getContentPane().add(btn1);
getContentPane().add(btn2);
pack();
setVisible(true);
}
public static void main(String[] args) {
JFrame frame =new ActionListenerDemo();
}
@Override
public void actionPerformed(ActionEvent e) {
//e是触发的事件对象
if(e.getSource()==btn1){
//通过getSource()获取激发事件的组件。
setTitle("Rosencrants");
}
else if(e.getSource()==btn2){
setTitle("Guidenstern");
}
}
}
- 除方法getSource()外,还可以调用ActionEvent对象的方法getActionCommand()来获得有关事件来源的更详细的信息。
- 默认情况下,动作命令(action Commend)是与组件相关联的文本,如JButton上的标签。您还可以调用组件的setActionCommend(String)方法来设置不同的动作命令。其中字符串参数是希望的动作命令文本。
- 当程序中多个组件可能触发相同的事件时,动作命令非常有用,例如程序中有一个Quit按钮,同时下按菜单中有一个Quit选项,通过将相同的动作命令指定为这两个组件,可以在事件处理方法中使用相同的处理代码来处理他们。
调整事件
- 调整事件是在用户移动JScrollBar组件(通过使用滚动条上的箭头、滑块、或者单击滚动条)时发生,要处理这些事件,类必须实现AdjustmentListener接口。
- adjustmentValueChanged(AdjustmentEvent)是AdjustmentListener接口中唯一的方法,格式如下:
public void adjustmentValueChanged(AdjustmentEvent evt){
}
- 要在事件处理方法中查看JScrollBar的当前值,可以调用AdjustmentEvent对象的getValue()方法。该方法返回一个表示滚动条的值的整数。
- getAdjustmentType()方法来判断用户移动滚动条的方式,该方式返回的是Adjustment类的类变量。
UNIT_INCREMENT:加1,可能是单击滚动条箭头或使用光标键的结果
UNIT_DECREMENT:减1,;
BLOCK_INCREMENT:增加较大的值,可能是在滚动条的滑块和箭头之间单击引起的
BLOCK_DECREMENT:减少较大的值。
实例
package ActionListenerDemo;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.JFrame;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class AdjustmentDemo extends JFrame implements AdjustmentListener {
JTextField value = new JTextField("50",30);
JScrollBar scrollBar =new JScrollBar(SwingConstants.CENTER,50,10,0,100);
//进度条初始值为50
public AdjustmentDemo(){
super("title bar");
setDefaultCloseOperation(EXIT_ON_CLOSE);
value.setHorizontalAlignment(SwingConstants.CENTER);
//设置文字居中显示
scrollBar.addAdjustmentListener(this);
getContentPane().add(value, "Center");
getContentPane().add(scrollBar, "South");
pack();
setVisible(true);
}
public static void main(String[] args) {
JFrame frame =new AdjustmentDemo();
}
@Override
public void adjustmentValueChanged(AdjustmentEvent e) {
if(e.getSource()==scrollBar){
value.setText(""+scrollBar.getValue());
}
}
}
焦点事件
- 焦点事件是在图形用户界面上的组件在获得或失去焦点时发生,获得焦点表明组件可以接受键盘输入,当文本框获得焦点时(在包含多个可编辑的文本框的用户界面中)时,其中将有一个闪烁的光标。文本将被输入到该组件中。
- 焦点适合于任何可接收输入的组件,获得焦点的组件有一个虚线框。
- 要处理焦点事件,类必须实现接口FocusListener。该接口包含两个方法:focusGained(FocusEvent)和focusLost(FocusEvent)。格式如下:
public void focusGained(focusEvent evt){
}
public void focusLost(focusEvent evt){
}
实例
package ActionListenerDemo;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class FocusDemo extends JFrame implements FocusListener {
JTextField tfTest[] = new JTextField[3];
int arr_size = 3;
public FocusDemo(){
super("title bar");
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(3,1));
for(int i=0;i<arr_size;i++){
tfTest[i] = new JTextField(i);
tfTest[i].addFocusListener(this);
getContentPane().add(tfTest[i]);
}
pack();
setVisible(true);
}
public static void main(String[] args) {
JFrame frame =new FocusDemo();
}
@Override
public void focusGained(FocusEvent e) {
JTextField mid = (JTextField)e.getSource();
mid.setText("获得了焦点");
}
@Override
public void focusLost(FocusEvent e) {
JTextField mid = (JTextField)e.getSource();
mid.setText("失去了焦点");
}
}
键盘事件
- 键盘事件在键盘上的键按下时发生,任何组件都可以激发这些事件,要支持这些事件,类必须实现KeyListener。
- 接口KeyListener中有三个方法:keyPressed(KeyEvent)、keyReleased(KeyEvent)、KeyTyped(KeyEvent)。它们的格式如下:
public void keyPressed(KeyEvent evt){//键盘按下
}
public void keyReleased(KeyEvent evt){//键盘释放
}
public void keyTyped(KeyEvent evt){//键盘按下又释放
}
- KeyEvent的方法getKeyChar()返回与事件相关联的键盘字符。如果没有与按下的键对应的Unicode,getKeyChar()将返回一个等于类变量KeyEvent.CHAR_UNDEFINED的字符值。
实例
package ActionListenerDemo;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class KeyListenerDemo extends JFrame implements KeyListener {
public KeyListenerDemo(){
super("title bar");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JTextField textField =new JTextField();
textField.addKeyListener(this);
getContentPane().add(textField, "Center");
pack();
setVisible(true);
}
public static void main(String[] args) {
JFrame frame =new KeyListenerDemo();
}
@Override
public void keyTyped(KeyEvent e) {
System.out.println("键入一个值");
}
@Override
public void keyPressed(KeyEvent e) {
System.out.println("键被按下");
}
@Override
public void keyReleased(KeyEvent e) {
System.out.println("键被释放");
}
}
鼠标事件
- 鼠标事件是由以下几种用户交互激发的
鼠标单击
鼠标进入组件区域
鼠标离开组件区域 - 任何组件都可以触发这些事件,类通过接口MouseListener来实现这些事件。该接口有五个方法:
mouseClicked(MouseEvent)//鼠标点击
mouseEntered(MouseEvent)//鼠标进入组件
mouseExit(MouseEvent)//鼠标离开组件
mousePressed(MouseEvent)//鼠标按下
mouseReleased(MouseEvent)//鼠标释放
格式为:
public void mousePressed(MouseEvent e) {
}
- 可用MouseEvent对象调用下述方法:
getClickCount() 返回一个整数,鼠标被单击的次数
getPoint():返回一个Point对象,指出单击位置在组件中的(x,y)坐标
getX():返回单击位置的x坐标
getY():返回单击位置的y坐标
鼠标移动事件
- 鼠标移动事件是在鼠标经过组件时发生,要支持这种事件,类必须实现接口MouseMotionListener。
- MouseMotionListener 接口有两个方法:mouseDragged(MouseEvent)和mouseMoved(MouseEvent),它们的格式:
public void mouseDragged(MouseEvent evt){
}//鼠标拖动时调用
public void mouseMoved(MouseEvent evt){
}//鼠标移动时调用
- 与其他的事件监听接口不同,MouseMotionListener并没有自己的事件类型,它使用的是MouseEvent对象。我们可以调用与鼠标事件相同的方法:getClick()、getPoint()、getX()、getY()。
实例
package ActionListenerDemo;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Paint;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class MouseMotionListenerDemo extends JFrame implements java.awt.event.MouseMotionListener{
public MouseMotionListenerDemo(){
super("title");
setSize(100, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JTextArea textArea =new JTextArea();
textArea.addMouseMotionListener(this);
getContentPane().add(textArea, "Center");
setVisible(true);
}
public static void main(String[] args) {
JFrame frame = new MouseMotionListenerDemo();
}
@Override
public void mouseDragged(MouseEvent e) {
Graphics g = getGraphics();//得到当前绘图环境
g.setColor(Color.RED);
g.drawLine(e.getX(), e.getY(), e.getX(), e.getY());
}
@Override
public void mouseMoved(MouseEvent e) {
System.out.println("鼠标位置: "+e.getX()+" "+e.getY());
}
}
选项事件
- 选项事件在下述组件中的选项被选中或者取消选中时发生:JButton,JCheckBox,JComboBox或JRadioButton。要处理这些事件,类必须实现借口ItemListener。
- ItemStateChanged(ItemEvent)是接口ItemEvent的唯一的一个方法。其格式如下:
void itemStateChanged(ItemEvent evt){
}
要确定事件发生在哪个选项上,可以调用ItemEvent对象的getEvent()方法。getItem()方法会触发两次ItemListener事件,一次是取消选中,一次是重新选中。
- 可以使用方法getStateChange()来判断选项是被选中还是被取消选中。该方法返回一个整数值,它等于类变量ItemEvent.DESELECTED或ItemEvent.SELETED。
实例
package ActionListenerDemo;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class ItemListenerDemo extends JFrame implements ItemListener{
public ItemListenerDemo(){
super("title");
setDefaultCloseOperation(EXIT_ON_CLOSE);
String sel[] = new String[]{"man","female","boy","girl"};
JComboBox cBoxTest = new JComboBox(sel);
cBoxTest.addItemListener(this);
getContentPane().setLayout(new FlowLayout());
getContentPane().add(cBoxTest);
pack();
setVisible(true);
}
public static void main(String[] args) {
JFrame frame =new ItemListenerDemo();
}
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange()==ItemEvent.SELECTED){
//如果不判断就输出,每次改变时,会输出两条,一条是取消选中的
//一条是重新选中的
System.out.println(e.getItem());
}
}
}
窗口事件
-
窗口事件在用户打开或者关闭诸如JFrame或JWindow等窗口对象时发生,任何组件都可以激发这种事件。要支持它们,类必须实现接口WindowListener。
-
接口WindowListener有七个方法:
windowActivated(WindowEvent)
windowClosed(WindowEvent)
windowClosing(WindowEvent)
windowDeactivated(WindowEvent)
windowDeiconified(WindowEvent)
windowIconified(WindowEvent)
windowOpended(WindowEvent) -
windowClosing()和windowClosed()极其类似,但前者在窗口正关闭时调用,后者在关闭后调用,实际上,可以在windowClosing()中才去措施来组织窗口关闭。