计算机外文翻译外文文献英文文献事件处理基础

上传人:痛*** 文档编号:46266168 上传时间:2021-12-11 格式:DOC 页数:19 大小:178.50KB
收藏 版权申诉 举报 下载
计算机外文翻译外文文献英文文献事件处理基础_第1页
第1页 / 共19页
计算机外文翻译外文文献英文文献事件处理基础_第2页
第2页 / 共19页
计算机外文翻译外文文献英文文献事件处理基础_第3页
第3页 / 共19页
资源描述:

《计算机外文翻译外文文献英文文献事件处理基础》由会员分享,可在线阅读,更多相关《计算机外文翻译外文文献英文文献事件处理基础(19页珍藏版)》请在装配图网上搜索。

1、外文原文Basics of Event Handling出处:Thinking in java作者: Bruce Eckel Any operating environment that supports GUIs constantly monitors events such as keystrokes or mouse clicks. The operating environment reports these events to the programs that are running. Each program then decides what, if anything, to

2、do in response to these events. In languages like Visual Basic, the correspondence between events and code is obvious. One writes code for each specific event of interest and places the code in what is usually called an event procedure. For example, a Visual Basic button named HelpButton would have

3、a Help Button_Click event procedure associated with it. The code in this procedure executes whenever that button is clicked. Each Visual Basic GUI component responds to a fixed set of events, and it is impossible to change the events to which a Visual Basic component responds.On the other hand, if y

4、ou use a language like raw C to do event-driven programming, you need to write the code that constantly checks the event queue for what the operating environment is reporting. This technique is obviously rather ugly, and, in any case, it is much more difficult to code. The advantage is that the even

5、ts you can respond to are not as limited as in languages, like Visual Basic, that go to great lengths to hide the event queue from the programmer.The Java programming environment takes an approach somewhat between the Visual Basic approach and the raw C approach in terms of power and, therefore, in

6、resulting complexity. Within the limits of the events that the AWT knows about, you completely control how events are transmitted from the event sources (such as buttons or scrollbars) to event listeners. You can designate any object to be an event listenerin practice, you pick an object that can co

7、nveniently carry out the desired response to the event. This event delegation model gives you much more flexibility than is possible with Visual Basic, in which the listener is predetermined, but it requires more code and is more difficult to untangle (at least until you get used to it).Event source

8、s have methods that allow you to register event listeners with them. When an event happens to the source, the source sends a notification of that event to all the listener objects that were registered for that event.As one would expect in an object-oriented language like Java, the information about

9、the event is encapsulated in an event object. In Java, all event objects ultimately derive from the class java.util.EventObject. Of course, there are subclasses for each event type, such as ActionEvent and WindowEvent.Different event sources can produce different kinds of events. For example, a butt

10、on can send ActionEvent objects, whereas a window can send WindowEvent objects.To sum up, heres an overview of how event handling in the AWT works. A listener object is an instance of a class that implements a special interface called (naturally enough) a listener interface. An event source is an ob

11、ject that can register listener objects and send them event objects. The event source sends out event objects to all registered listeners when that event occurs. The listener objects will then use the information in the event object to determine their reaction to the event.You register the listener

12、object with the source object by using lines of code that follow the modeleventSourceObject.addEventListener(eventListenerObject);Here is an example:ActionListener listener = . . .;JButton button = new JButton(Ok);button.addActionListener(listener);Now the listener object is notified whenever an act

13、ion event occurs in the button. For buttons, as you might expect, an action event is a button click.Code like the above requires that the class to which the listener object belongs implements the appropriate interface (which in this case is the ActionListener interface). As with all interfaces in Ja

14、va, implementing an interface means supplying methods with the right signatures. To implement the ActionListener interface, the listener class must have a method called actionPerformed that receives an ActionEvent object as a parameter.class MyListener implements ActionListener . . . public void act

15、ionPerformed(ActionEvent event) / reaction to button click goes here . . . Whenever the user clicks the button, the JButton object creates an ActionEvent object and calls listener.actionPerformed(event), passing that event object. It is possible for multiple objects to be added as listeners to an ev

16、ent source such as a button. In that case, the button calls the actionPerformed methods of all listeners whenever the user clicks the button.Figure 8-1 shows the interaction between the event source, event listener, and event object.Figure 8-1. Event notificationExample: Handling a Button ClickAs a

17、way of getting comfortable with the event delegation model, lets work through all details needed for the simple example of responding to a button click. For this example, we will want A panel populated with three buttons; and Three listener objects that are added as action listeners to the buttons.W

18、ith this scenario, each time a user clicks on any of the buttons on the panel, the associated listener object then receives an ActionEvent that indicates a button click. In our sample program, the listener object will then change the background color of the panel.Before we can show you the program t

19、hat listens to button clicks, we first need to explain how to create buttons and how to add them to a panel. (For more on GUI elements, see Chapter 9.)You create a button by specifying a label string, an icon, or both in the button constructor. Here are two examples:JButton yellowButton = new JButto

20、n(Yellow);JButton blueButton = new JButton(new ImageIcon(blue-ball.gif);Adding buttons to a panel occurs through a call to a method named (quite mnemonically) add. The add method takes as a parameter the specific component to be added to the container. For example,class ButtonPanel extends JPanel pu

21、blic ButtonPanel() JButton yellowButton = new JButton(Yellow); JButton blueButton = new JButton(Blue); JButton redButton = new JButton(Red); add(yellowButton); add(blueButton); add(redButton); Figure 8-2 shows the result.Figure 8-2. A panel filled with buttonsNow that you know how to add buttons to

22、a panel, youll need to add code that lets the panel listen to these buttons. This requires classes that implement the ActionListener interface, which, as we just mentioned, has one method: actionPerformed, whose signature looks like this:public void actionPerformed(ActionEvent event)NOTE: The Action

23、Listener interface we used in the button example is not restricted to button clicks. It is used in many separate situations: When an item is selected from a list box with a double click; When a menu item is selected; When the ENTER key is clicked in a text field; When a certain amount of time has el

24、apsed for a Timer component.You will see more details in this chapter and the next.The way to use the ActionListener interface is the same in all situations: the actionPerformed method (which is the only method in ActionListener) takes an object of type ActionEvent as a parameter. This event object

25、gives you information about the event that happened.When a button is clicked, then we want to set the background color of the panel to a particular color. We store the desired color in our listener class.class ColorAction implements ActionListener public ColorAction(Color c) backgroundColor = c; pub

26、lic void actionPerformed(ActionEvent event) / set panel background color . . . private Color backgroundColor;We then construct one object for each color and set the objects as the button listeners.ColorAction yellowAction = new ColorAction(Color.YELLOW);ColorAction blueAction = new ColorAction(Color

27、.BLUE);ColorAction redAction = new ColorAction(Color.RED);yellowButton.addActionListener(yellowAction);blueButton.addActionListener(blueAction);redButton.addActionListener(redAction);For example, if a user clicks on the button marked Yellow, then the actionPerformed method of the yellowAction object

28、 is called. Its backgroundColor instance field is set to Color.YELLOW, and it can now proceed to set the panels background color.Just one issue remains. The ColorAction object doesnt have access to the panel variable. You can solve this problem in two ways. You can store the panel in the ColorAction

29、 object and set it in the ColorAction constructor. Or, more conveniently, you can make ColorAction into an inner class of the ButtonPanel class. Its methods can then access the outer panel automatically. (For more information on inner classes, see Chapter 6.)We follow the latter approach. Here is ho

30、w you place the ColorAction class inside the ButtonPanel class.class ButtonPanel extends JPanel. . .private class ColorAction implements ActionListener. . .public void actionPerformed(ActionEvent event)setBackground(backgroundColor);/ i.e.,outer.setBackground(.)private Color backgroundColor;Look clo

31、sely at the actionPerformed method. The ColorAction class doesnt have a setBackground method. But the outer ButtonPanel class does. The methods are invoked on the ButtonPanel object that constructed the inner class objects. (Note again that outer is not a keyword in the Java programming language. We

32、 just use it as an intuitive symbol for the invisible outer class reference in the inner class object.)This situation is very common. Event listener objects usually need to carry out some action that affects other objects. You can often strategically place the listener class inside the class whose s

33、tate the listener should modify.Becoming Comfortable with Inner ClassesSome people dislike inner classes because they feel that a proliferation of classes and objects makes their programs slower. Lets have a look at that claim. You dont need a new class for every user interface component. In our exa

34、mple, all three buttons share the same listener class. Of course, each of them has a separate listener object. But these objects arent large. They each contain a color value and a reference to the panel. And the traditional solution, with if . . . else statements, also references the same color obje

35、cts that the action listeners store, just as local variables and not as instance fields.We believe the time has come to get used to inner classes. We recommend that you use dedicated inner classes for event handlers rather than turning existing classes into listeners. We think that even anonymous in

36、ner classes have their place.Here is a good example of how anonymous inner classes can actually simplify your code. If you look at the code of Example 8-1, you will note that each button requires the same treatment:1.Construct the button with a label string.2. Add the button to the panel.3.Construct

37、 an action listener with the appropriate color.4. Add that action listener.Lets implement a helper method to simplify these tasks:void makeButton(String name, Color backgroundColor) JButton button = new JButton(name); add(button); ColorAction action = new ColorAction(backgroundColor); button.addActi

38、onListener(action);Then the ButtonPanel constructor simply becomespublic ButtonPanel() makeButton(yellow, Color.YELLOW); makeButton(blue, Color.BLUE); makeButton(red, Color.RED);Now you can make a further simplification. Note that the ColorAction class is only needed once: in the makeButton method.

39、Therefore, you can make it into an anonymous class:void makeButton(String name, final Color backgroundColor) JButton button = new JButton(name); add(button); button.addActionListener(new ActionListener() public void actionPerformed(ActionEvent event) setBackground(backgroundColor); );The action list

40、ener code has become quite a bit simpler. The actionPerformed method simply refers to the parameter variable backgroundColor.No explicit constructor is needed. As you saw in Chapter 6, the inner class mechanism automatically generates a constructor that stores all local final variables that are used

41、 in one of the methods of the inner class.TIP: Anonymous inner classes can look confusing. But you can get used to deciphering them if you train your eyes to glaze over the routine code, like this:button.addActionListener(new ActionListener() public void actionPerformed(ActionEvent event) setBackgro

42、und(backgroundColor); );That is, the button action sets the background color. As long as the event handler consists of just a few statements, we think this can be quite readable, particularly if you dont worry about the inner class mechanics.TIP: JDK 1.4 introduces a mechanism that lets you specify

43、simple event listeners without programming inner classes. For example, suppose you have a button labeled Load whose event handler contains a single method call:frame.loadData();Of course, you can use an anonymous inner class:loadButton.addActionListener(new ActionListener() public void actionPerform

44、ed(ActionEvent event) frame.loadData(); );But the EventHandler class can create such a listener automatically, with the callEventHandler.create(ActionListener.class, frame, loadData)Of course, you still need to install the handler:loadButton.addActionListener(ActionListener) EventHandler.create(Acti

45、onListener.class, frame, loadData);The cast is necessary because the create method returns an Object. Perhaps a future version of the JDK will make use of generic types to make this method even more convenient.If the event listener calls a method with a single parameter that is derived from the even

46、t handler, then you can use another form of the create method. For example, the callEventHandler.create(ActionListener.class, frame, loadData, source.text)is equivalent tonew ActionListener() public void actionPerformed(ActionEvent event) frame.loadData(JTextField) event.getSource().getText(); Note

47、that the event handler turns the names of the properties source and text into method calls getSource and getText, using the JavaBeans convention. (For more information on properties and JavaBeans components, please turn to Volume 2.)However, in practice, this situation is not all that common, and th

48、ere is no mechanism for supplying parameters that arent derived from the event object.事件处理基础任何支持GUI的操作环境都要不断地监视敲击键盘或点击鼠标这样的事件。操作环境将这些事件报告给正在运行的应用程序。如果有事件产生,每个应用程序将决定如何对它们做出响应。在Visual Basic这样的语言中,事件与代码之间的对应是明确的。程序员对相关的特定事件编写代码,并将这些代码放置在过程中,通常人们将他们称为事件过程。例如,一个名为HelpButton的Visual Basic按钮有一个与之相关的HelpBut

49、ton_Click事件过程。这个过程中的代码将在点击按钮后执行。每个Visual Basic的GUI组件都响应一个固定的事件集, Visual Basic组件响应的事件集是不能改变的。另一方面,如果使用象原始C这样的语言进行事件驱动的程序设计,就需要编写代码来不断地检查事件队列,以便查询操作环境报告的内容。显然,这种方式编写的程序可读性很差,而且在有些情况下,编码的难度也非常大。它的好处在于响应的事件不受限制,而不象Visual Basic这样的语言,将事件队列对程序员隐藏起来。JAVA程序设计环境折中了Visual Basic与原始C的事件处理方式,因此,它既有着强大的功能,又具有一定的复杂

50、性。在AWT所知的事件范围内,可以完全控制事件从事件源(例如按钮或滚动条)到事件监听器的传递过程,并将任何对象指派给事件监听器。不过事实上,应该选择一个能够便于响应事件的对象。这种事件委托模型与Visual Basic那种预定义的监听器模型比较起来更加灵活,但却需要编写更多的代码,整理起来也非常困难(至少熟悉它之前)。事件源有一些向其注册事件监听器的方法。当某个事件源产生事件的时候,事件源会向所有事件监听器对象发送一个通告,当然这些事件监听器事先已经为事件注册过了。像JAVA这样的面向对象语言,都将事件的相关信息封装在一个事件对象中。在JAVA中,所有的事件对象都最终派生于java.util.

51、EventObject类。当然,每个事件类型还有子类,例如,ActionEvent和WindowEvent。不同的事件源可以产生不同类型的事件。例如,按钮可以发送一个ActionEvent对象,而窗口可以发送WindowEvent对象。综上所述,下面给出了AWT事件处理机制的概要:监听器对象是一个实现了特定接口的类的实例事件源是一个能够注册监听器对象并发送事件对象的对象当事件发生时,事件源将事件对象传递给所有注册的监听器监听器对象将利用事件对象中的信息决定如何对事件做出响应可以利用下列代码模型来为事件源对象注册监听器对象:eventSourceObject.addEventListener(e

52、ventListenerObject);下面是一个例子:ActionListener listener=.;JButton button=new JButton(OK);button.addActionListener(listener);现在,只要按钮产生了一个“动作事件”,listener对象就会得到通告。对于按钮来说,动作事件就是点击按钮。上面的代码要求监听器对象所属的类必须实现相应的接口(在这个例子中是ActionListener接口)。与JAVA中所有的接口一样,实现一个接口就意味着要用完全相同的签名实现每个方法。为了实现ActionListener接口,监听器类必须有一个被称为Ac

53、tionPerformed的方法,该方法接受一个ActionEvent对象参数。class MyListener implents ActionListenerpublic void actionPerformed(ActionEvent event)/reaction to button click goes here 只要用户点击按钮,JButton对象就会创建一个AtionEvent对象,然后调用listener.actionPormed(event)传递事件对象。可以将多个监听器对象添加到一个像按钮这样的事件源中。这样一来,只要用户点击按钮,按钮就会调用所有监听器的actionPerf

54、orned方法。图8-1显示了事件源、事件监听器和事件对象之间的协作关系。处理按钮点击事件例子 为了加深对事件委托模型的理解,下面以一个响应按钮点击事件的简单例子来说明所需要知道的所有细节。在这个例子中,我们想要: 在一个面板中放置三个按钮 添加三个监听器对象用来作为按钮的动作监听器 在这个情况下,只要用户点击面板上的任何一个按钮,相关的监听器对象就会接受到一个ActionEvent对象,它表示有个按钮被点击了。在示例程序中,监听器对象将改变面板的背景颜色。在演示如何监听按钮点击事件之前,首先需要讲解一下如何创建按钮以及如何将它们添加到面板中。图 8-1. 事件通告 可以通过在按钮构造器中指定

55、一个标签字符串、一个图标或两项都指定来创建一个按钮。下面是两个例子: JButton yellowButton=new JButton(Yellow); JButton blueButton=new JButton(new ImageIon(blue-ball.gif); 将按钮添加到面板中需要调用 add方法(十分容易记忆)。add方法的参数指定了将要放置到容器中的组件。例如, class ButtonPanel extends JPanel public ButtonPanel() JButton yellowButton=new JButton(Yellow); JButton blue

56、Button=new JButton(Blue); JButton redButton=new JButton(Red); add(yellowButton); add(blueButton); add(redButton); 图8-2显示了结果。图8-2添上按钮的面板 至此,知道了如何将按钮添加到面板上,接下来需要增加让面板监听这些按钮的代码。这需要一个实现ActionListener接口的类,如前所述,它应该包含一个actionPerformed方法,其签名为:public void actionPerformed(ActionEvent event)注意:在按钮例子中使用的ActionL

57、istener接口并不仅限于按钮点击事件。它可以应用于很多情况: 当采用鼠标双击的方式选择了列表框中的一个选项时 当选择一个菜单项时 当在文本域中敲击ENTER时 对于一个Timer组件来说,当到达指定的时间间隔时在本章和下一章中,将会看到更加详细的内容。在各种情况下,使用ActionListener接口的方式都是一样的:actionPerformed方法(ActionListener中的唯一方法)将接受一个ActionEvent类型的对象作为参数。这个事件对象包含了事件发生时的相关信息。当按钮被点击时,我们希望将面板的背景颜色设置为指定的颜色。该颜色存储在监听器类中。Class ColorA

58、ction implants ActionLostener public ColorAction(Color c) backgroundColor=c;public void actionPerformed(ActionEvent event)/ set panel background colorprivate Color backgroundColor;然后,为每种颜色构造一个对象,并将这些对象设置为按钮对象监听器。ColorAction yellowAction = new ColorAction(Color.YELLOW);ColorAction blueAction = new Co

59、lorAction(Color.BLUE);ColorAction redAction = new ColorAction(Color.RED);yellowButton.addActionListener(yellowAction);blueButton.addActionListener(blueAction);redButton.addActionListener(redAction);例如,如果一个用户在标有“Yellow”的按钮上点击了一下,那么yellowAction对象的actionPerformed方法就会被调用。这个对象的backgroundColor实例域设置为Color.

60、YELLOW,现在就将面板的背景设置为黄色了。这里还有一个需要考虑的问题。ColorAction对象没有权限访问panel变量。可以采用两种方式解决这个问题。一个是将面板存储在ColorAction对象中,并在ColorAction构造器中设置它;另一个是将ColorAction作为ButtonPanel类的内部类。这样一来,ColorAction就自动地拥有访问外部类的权限了(有关内部类的详细介绍请参阅第6章)。这里使用第二种方法。下面说明一下如何将ColorAction类放置在ButtonPanel中。class ButtonPanel extends JPanel. . .private

61、 class ColorAction implements ActionListener. . .public void actionPerformed(ActionEvent event)setBackground(backgroundColor);/ i.e.,outer.setBackground(.)private Color backgroundColor;下面仔细地研究一下actionPerformed方法。在ColorAction类中没有setBackground方法,但在外部ButtonPanel类中却有,这个方法可以在ButtonPanel对象构造内部对象之后调用(再次说明一

62、下,outer不是JAVA程序设计语言的关键字,它只是一种表示符号,用于表示内部类对象不可见的外部类引用。)。这种情形十分常见。事件监听器对象通常需要执行一些对其他对象可能产生影响的操作。可以策略性地将监听器类放置在需要修改状态的那个类中。使用内部类好处有些人不喜欢使用内部类,其原因是觉得类和对象的增加会使得程序的执行速度变慢。下面让我们讨论一下这个问题。首先,不需要为每个用户界面组件定义一个新类。在前面列举的例子中三个按钮共享同一个监听器类。当然,每个按钮分别使用不同的监听器对象。但是,这些对象并不大,它们只包含一个颜色值和一个面板的引用。而使用传统的ifelse语句的解决方案,还需要引用动作监听器存储的上述颜色对象,只不过这是一个局部变量,而不是实例域。我们认为现在已经到了习惯使用内部类的时代了。我们建议为每个事件处理设计一个专门的内部类;而不要将一个已经存在的类转换为监听器,即使匿名内部类也有一定的应用场合。下面是一个说明使用匿名内部类简化代码的例子。如果仔细看一下例8-1的代码,就会注意到每个按钮的处理过程都是一样的:1 用标签字符串构造按钮2 将按钮添加到面板上3 用适当的颜色构造

展开阅读全文
温馨提示:
1: 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
2: 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
3.本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
5. 装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
关于我们 - 网站声明 - 网站地图 - 资源地图 - 友情链接 - 网站客服 - 联系我们

copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!