Basic GUI Components: Java: How To Program Chapter 14 (Continued)
Basic GUI Components: Java: How To Program Chapter 14 (Continued)
Focus: Event Handling in Java's Graphical User Interface GUIs are event driven
You can include Swing and AWT components on the same GUI. The picture below shows the difference between AWT and Swing:
Must create a class that represents the event handler and implements an appropriate interfaceknown as an event-listener interface.
In Craps.java, the Craps class implemented Actionlistener and declared the only method for that interface -> actionPerformed, satisfying this step.
2.
Must indicate that an object of the class from Step 1 should be notified when the event occursknown as registering the event handler.
In Craps.java, this step was accomplished (for the roll Jbutton) by the following:
Roll.addActionListener(this); The addActionListener argument is an ActionListener object, which in this case is the current instance of the Craps object
5
Instead, class TextFieldHandler implements the ActionListener interface and therefore defines actionPerformed.
When the user presses ENTER while one of the JTextFields or JPasswordFields has focus, causes the system to generate an ActionEvent object
ActionEvent objects contain information about the event that just occurred, such as: the event source the text in the text field.
The ActionEvent is processed by an object that implements the ActionListener interface (in our example: TextFieldHandler) The TextFieldHandler class satisfies #1 in slide 3 But before this can occur, the program must register the TextFieldHandler object as the event handler for the JTextFields and the JPasswordField. TextField1.addActionListener(handler); registers handler (which is of type TextFieldHandler) as the event handler for the TextField1 component Satisfies #2 in slide 3
11
Implementing KeyListener will allow you to create a dynamic response to users pressing ANY key
In our last example, only pressing enter would generate an event Must declare the methods: keyPressed (called when any key is pressed) keyTyped (called in response to pressing any key that is not an action key
Action keys:arrows, home, end, page up, page down, any function keyall non-characters
keyReleased (called when any key is released) Must register with addKeyListener(KeyEvent) method
12
13
event processing is delegated to a particular object (the event listener) within a program use of delegation allows more than one event of the same type to be handled by the program (ie., multiple JButton's)
14
actionListeners:
JButtons (command buttons), JTextFields, JPasswordFields JCheckBoxs (true/false values), JToggleButtons (used with toolbars), and JRadioButtons (on/off values) JComboBox (drop-down lists) more than one component of same listener type can be used, if so, "delegation event model" object (usually an inner class) is used to parse out program's course of action
itemListeners:
15
18 19 21 22 23 24 25
57 }
17