计算机外文翻译外文文献英文文献事件处理基础.doc_第1页
计算机外文翻译外文文献英文文献事件处理基础.doc_第2页
计算机外文翻译外文文献英文文献事件处理基础.doc_第3页
计算机外文翻译外文文献英文文献事件处理基础.doc_第4页
计算机外文翻译外文文献英文文献事件处理基础.doc_第5页
已阅读5页,还剩3页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

外文原文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 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 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 you 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 events 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 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 conveniently 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 sources 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 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 button 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 object 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 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 action 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 java, 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 actionperformed(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 event 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 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.with 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 that 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 jbutton(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 public 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 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 actionlistener 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 elapsed 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 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; public 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.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 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 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 how 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 closely 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 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 state 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 example, 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 objects 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 inner 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 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.addactionlistener(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. 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 listener 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 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) setbackground(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 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 actionperformed(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(actionlistener.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 event 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 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 there is no mechanism for supplying parameters that arent derived from the event object.事件处理基础任何支持gui的操作环境都要不断地监视敲击键盘或点击鼠标这样的事件。操作环境将这些事件报告给正在运行的应用程序。如果有事件产生,每个应用程序将决定如何对它们做出响应。在visual basic这样的语言中,事件与代码之间的对应是明确的。程序员对相关的特定事件编写代码,并将这些代码放置在过程中,通常人们将他们称为事件过程。例如,一个名为helpbutton的visual basic按钮有一个与之相关的helpbutton_click事件过程。这个过程中的代码将在点击按钮后执行。每个visual basic的gui组件都响应一个固定的事件集, visual basic组件响应的事件集是不能改变的。另一方面,如果使用象原始c这样的语言进行事件驱动的程序设计,就需要编写代码来不断地检查事件队列,以便查询操作环境报告的内容。显然,这种方式编写的程序可读性很差,而且在有些情况下,编码的难度也非常大。它的好处在于响应的事件不受限制,而不象visual basic这样的语言,将事件队列对程序员隐藏起来。java程序设计环境折中了visual basic与原始c的事件处理方式,因此,它既有着强大的功能,又具有一定的复杂性。在awt所知的事件范围内,可以完全控制事件从事件源(例如按钮或滚动条)到事件监听器的传递过程,并将任何对象指派给事件监听器。不过事实上,应该选择一个能够便于响应事件的对象。这种事件委托模型与visual basic那种预定义的监听器模型比较起来更加灵活,但却需要编写更多的代码,整理起来也非常困难(至少熟悉它之前)。事件源有一些向其注册事件监听器的方法。当某个事件源产生事件的时候,事件源会向所有事件监听器对象发送一个通告,当然这些事件监听器事先已经为事件注册过了。像java这样的面向对象语言,都将事件的相关信息封装在一个事件对象中。在java中,所有的事件对象都最终派生于java.util.eventobject类。当然,每个事件类型还有子类,例如,actionevent和windowevent。不同的事件源可以产生不同类型的事件。例如,按钮可以发送一个actionevent对象,而窗口可以发送windowevent对象。综上所述,下面给出了awt事件处理机制的概要:监听器对象是一个实现了特定接口的类的实例事件源是一个能够注册监听器对象并发送事件对象的对象当事件发生时,事件源将事件对象传递给所有注册的监听器监听器对象将利用事件对象中的信息决定如何对事件做出响应可以利用下列代码模型来为事件源对象注册监听器对象:eventsourceobject.addeventlistener(eventlistenerobject);下面是一个例子:actionlistener listener=.;jbutton button=new jbutton(ok);button.addactionlistener(listener);现在,只要按钮产生了一个“动作事件”,listener对象就会得到通告。对于按钮来说,动作事件就是点击按钮。上面的代码要求监听器对象所属的类必须实现相应的接口(在这个例子中是actionlistener接口)。与java中所有的接口一样,实现一个接口就意味着要用完全相同的签名实现每个方法。为了实现actionlistener接口,监听器类必须有一个被称为actionperformed的方法,该方法接受一个actionevent对象参数。class mylistener implents actionlistenerpublic void actionperformed(actionevent event)/reaction to button click goes here 只要用户点击按钮,jbutton对象就会创建一个ationevent对象,然后调用listener.actionpormed(event)传递事件对象。可以将多个监听器对象添加到一个像按钮这样的事件源中。这样一来,只要用户点击按钮,按钮就会调用所有监听器的actionperforned方法。图8-1显示了事件源、事件监听器和事件对象之间的协作关系。处理按钮点击事件例子 为了加深对事件委托模型的理解,下面以一个响应按钮点击事件的简单例子来说明所需要知道的所有细节。在这个例子中,我们想要: 在一个面板中放置三个按钮 添加三个监听器对象用来作为按钮的动作监听器 在这个情况下,只要用户点击面板上的任何一个按钮,相关的监听器对象就会接受到一个actionevent对象,它表示有个按钮被点击了。在示例程序中,监听器对象将改变面板的背景颜色。在演示如何监听按钮点击事件之前,首先需要讲解一下如何创建按钮以及如何将它们添加到面板中。图 8-1. 事件通告 可以通过在按钮构造器中指定一个标签字符串、一个图标或两项都指定来创建一个按钮。下面是两个例子: 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 bluebutton=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)注意:在按钮例子中使用的actionlistener接口并不仅限于按钮点击事件。它可以应用于很多情况: 当采用鼠标双击的方式选择了列表框中的一个选项时 当选择一个菜单项时 当在文本域中敲击enter时 对于一个timer组件来说,当到达

温馨提示

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

评论

0/150

提交评论