Java进阶-事件响应

GUI中,我们看到了如何用图形树来组织一个图形界面。然而,这样的图形界面是静态的。我们无法互动的对该界面进行操作。GUI的图形元素需要增加事件响应(event handling),才能得到一个动态的图形化界面。

元素, 事件, 监听器

我们在GUI一文中提到了许多图形元素。有一些事件(Event)可能发生在这些图形元素上,比如:

  • 点击按钮

  • 拖动滚动条

  • 选择菜单

Java中的事件使用对象表示,比如ActionEvent。每个事件有作用的图形对象,比如按钮,滚动条,菜单。

 

所谓互动的GUI,是指当上面事件发生时,会有相应的动作产生,比如:

  • 改变颜色

  • 改变窗口内容

  • 弹出菜单

每个动作都针对一个事件。我们将动作放在一个监听器(ActionListener)中,然后让监听器监视(某个图形对象)的事件。当事件发生时,监听器中的动作随之发生。

 

 

因此,一个响应式的GUI是图形对象、事件对象、监听对象三者互动的结果。我们已经知道了如何创建图形对象。我们需要给图形对象增加监听器,并让监听器捕捉事件。

 

按钮响应

下面实现一个响应式的按钮。在点击按钮之后,面板的颜色会改变,如下图:

 (这个例子改编自Core Java 2,Volume 1, Example 8-1)

package blogjavaTest;

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

public class HelloWorldSwing {
	private static void createAndShowGUI() {
		JFrame frame = new JFrame("HelloWorld");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// Pane's layout
		Container cp = frame.getContentPane();
		cp.setLayout(new FlowLayout());

		// add interactive panel to Content Pane
		cp.add(new ButtonPanel());

		// show the window
		frame.pack();
		frame.setVisible(true);
	}

	public static void main(String[] args) {
		Runnable tr = new Runnable() {
			public void run() {
				createAndShowGUI();
			}
		};
		javax.swing.SwingUtilities.invokeLater(tr);
	}
}

/**
 * JPanel with Event Handling
 */
class ButtonPanel extends JPanel {
	public ButtonPanel() {
		JButton yellowButton = new JButton("Yellow");
		JButton redButton = new JButton("Red");

		this.add(yellowButton);
		this.add(redButton);

		/**
		 * register ActionListeners
		 */
		ColorAction yellowAction = new ColorAction(Color.yellow);
		ColorAction redAction = new ColorAction(Color.red);

		yellowButton.addActionListener(yellowAction);
		redButton.addActionListener(redAction);
	}

	/**
	 * ActionListener as an inner class
	 */
	private class ColorAction implements ActionListener {
		public ColorAction(Color c) {
			backgroundColor = c;
		}

		/**
		 * Actions
		 */
		public void actionPerformed(ActionEvent event) {
			setBackground(backgroundColor); // outer object, JPanel method
			repaint();
		}

		private Color backgroundColor;
	}
}


上面,我们用一个内部类ColorAction来实施ActionListener接口。这样做是为了让监听器能更方便的调用图形对象的成员,比如setBackground()方法。

ActionListener的actionPerformed()方法必须被覆盖。该方法包含了事件的对应动作。该方法的参数为事件对象,即监听ActionEvent类型的事件。ActionEvent是一个高层的类,Java会找到图形对象(按钮)会发生的典型事件(点击)作为事件

ColorAction生成的对象即为监听器对象。

 

我们为两个按钮JButton添加了相应的监听器对象。当有事件发生时,对应动作将随之产生。

 

总结

ActionListener interface

ActionEvent class


转载于:https://my.oschina.net/xuliblog/blog/607759

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值