Question: If you want to prevent the character represented by a KeyEvent from being added to a TextField, what should you do ing the keyTyped method of a listener getting the event? a. Execute the KeyEvent object's consume method. b. Return true from the keyTyped method. c. Call the KeyEvent object's setKeyChar method with a zero value. d. Get the current text from the TextField, remove the last character from the String. The answer is A. Could anyone explain why? Ada
Ada Wang
Greenhorn
Joined: Aug 28, 2000
Posts: 23
posted
0
I really need your help. Ada
Ajith Kallambella
Sheriff
Joined: Mar 17, 2000
Posts: 5781
posted
0
I am not an AWT expert, but let me try. KeyEvent derives from java.awt.event.InputEvent class which is the root class for all component-level input events. Input events are delivered to listeners before they are processed normally by the source where they originated. The InputEvent class derives the consume() method from the (abstract) AWTEvent superclass. You can subclass AWTEvent or InputEvent to provide custom events and override the consume method, if need be. Look at the method documentation
public void consume() Consumes this event so that it will not be processed in the default manner by the source which originated it.
This means if you don't want the event to be processed, you just gobble it, so that no one else sees it. That's what the consume method does. For example, consuming mousePressed events on a Button component will prevent the Button from being activated IMO the best way to experience this phenomenon is by writing some code. Give it a try! If you get stuck, I will help you Ajith
Open Group Certified Master IT Architect.
Sun Certified Architect(SCEA).
Ada Wang
Greenhorn
Joined: Aug 28, 2000
Posts: 23
posted
0
Ajith, After I subclass AWTEvent providing my event and override the consume() method, how should I associate my event to the visual component(let's say a button)? Ada
Ajith Kallambella
Sheriff
Joined: Mar 17, 2000
Posts: 5781
posted
0
Ada, To begin with you can try playing with some of the existing AWTEvent subclasses that implements the consume(). I wrote a small program to help you get started. The following program is built on your question which creates a read-only text area. The listener simply consumes the KeyTyped event thus blocking further default processing. Hence all inputs from the user are ignored and the text remains the same. The code is simple and self documented, so I will not deliberate on how it is written. Try it out and have fun!