欢迎来到淘文阁 - 分享文档赚钱的网站! | 帮助中心 好文档才是您的得力助手!
淘文阁 - 分享文档赚钱的网站
全部分类
  • 研究报告>
  • 管理文献>
  • 标准材料>
  • 技术资料>
  • 教育专区>
  • 应用文书>
  • 生活休闲>
  • 考试试题>
  • pptx模板>
  • 工商注册>
  • 期刊短文>
  • 图片设计>
  • ImageVerifierCode 换一换

    计算机-外文翻译-外文文献-英文文献-事X件处理基础.doc

    • 资源ID:87909831       资源大小:198.50KB        全文页数:19页
    • 资源格式: DOC        下载积分:8金币
    快捷下载 游客一键下载
    会员登录下载
    微信登录下载
    三方登录下载: 微信开放平台登录   QQ登录  
    二维码
    微信扫一扫登录
    下载资源需要8金币
    邮箱/手机:
    温馨提示:
    快捷下载时,用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)。
    如填写123,账号就是123,密码也是123。
    支付方式: 支付宝    微信支付   
    验证码:   换一换

     
    账号:
    密码:
    验证码:   换一换
      忘记密码?
        
    友情提示
    2、PDF文件下载后,可能会被浏览器默认打开,此种情况可以点击浏览器菜单,保存网页到桌面,就可以正常下载了。
    3、本站不支持迅雷下载,请使用电脑自带的IE浏览器,或者360浏览器、谷歌浏览器下载即可。
    4、本站资源下载后的文档和图纸-无水印,预览文档经过压缩,下载后原文更清晰。
    5、试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓。

    计算机-外文翻译-外文文献-英文文献-事X件处理基础.doc

    外文原文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, here's 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, let's 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, you'll 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 panel's background color.Just one issue remains. The ColorAction object doesn't 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 doesn't 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. Let's have a look at that claim. You don't 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 aren't 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.Let's 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 don't 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 aren't derived from the event object.

    注意事项

    本文(计算机-外文翻译-外文文献-英文文献-事X件处理基础.doc)为本站会员(教****)主动上传,淘文阁 - 分享文档赚钱的网站仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知淘文阁 - 分享文档赚钱的网站(点击联系客服),我们立即给予删除!

    温馨提示:如果因为网速或其他原因下载失败请重新下载,重复下载不扣分。




    关于淘文阁 - 版权申诉 - 用户使用规则 - 积分规则 - 联系我们

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

    工信部备案号:黑ICP备15003705号 © 2020-2023 www.taowenge.com 淘文阁 

    收起
    展开