html5-img
1 / 63

COMP201 Java Programming

COMP201 Java Programming. Topic 9: Event Handling Reading: Chapter 8. Objective and Outline. Objective: Show how to write GUI programs that react to user actions. Outline: Java AWT event delegation model An example The AWT event hierarchy Individual events KeyEvents MouseEvents

Download Presentation

COMP201 Java Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. COMP201 Java Programming Topic 9: Event Handling Reading: Chapter 8

  2. Objective and Outline • Objective: • Show how to write GUI programs that react to user actions. • Outline: • Java AWT event delegation model • An example • The AWT event hierarchy • Individual events • KeyEvents • MouseEvents • Special classes and interfaces for event handling • Adapter classes • The Action interface

  3. Java AWT event delegation model • Java automatically generates event objects when • Mouse or button clicked • Menu, checkbox, or text selected • Keyboard typed • Scrollbar adjusted • ….. • It is up to the programmer to decide whether to do anything or what to do when an event happens

  4. Event Objectevt Event Source Event Listener Java AWT event delegation model • Event source: • An object that generates events • Listener: • Receives events and decides what to do

  5. Java AWT event delegation model • Notes • A listener must be registered with an event source in order to listen for events produced there. • An event source can have multiple listeners and vice versa • A listener class must implement a listener interface, which decides the response to an event.

  6. Event Objectevt Event Source Event Listener Java AWT event delegation model Has to register its own listeners Source.addActionListener(Listener) Any objects of class that implements an appropriate listener interface class Listener implements ActionListener { … actionPerformed(Event evt) {…} }

  7. Event Objectevt Event Source Event Listener Java AWT event delegation model • The event handling process: • When an event occurs, event source sends event objects to allregistered listeners. • Listeners use information encapsulated in the event objects to determine what to do.

  8. Example • A button that beeps when clicked (Beeper.java) • Create a GUI with one button class BeeperFrame extends JFrame { public BeeperFrame() { setSize( 300, 200); button = newJButton("Click Me"); getContentPane().add(button, BorderLayout.CENTER); } private JButton button; } Javax.swing.JButton has five constructors Java.awt.Container void add(Component) Adding button directly onto contentPane. Bad programming style.

  9. Example • When a button is clicked, an ActionEvent object is produced (java.awt.event.ActionEvent). • Listener for an ActionEvent: an object of a class that implements the ActionListener Interface • class ClickListener implementsActionListener { public voidactionPerformed(ActionEvent e) { Toolkit.getDefaultToolkit().beep(); } }

  10. Example • Create a listener object and register it with the button: class BeeperFrame extends JFrame { public BeeperFrame() { … button = newJButton("Click Me"); button.addActionListener(new ClickListener()); } } • The driver class: public class Beeper { public static void main(String[] args) { BeeperFrame frame = new BeeperFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); } } //Check out Beeper1.java (inner class)

  11. Outline • Outline: • Java AWT event delegation model • Two examples • The AWT event hierarchy • Individual events • KeyEvents • MouseEvents • Special classes and interfaces for event handling • Adapter classes • The Action interface

  12. EventObject AWTEvent Action Event Adjustment Event Component Event Item Event Text Event Container Event Focus Event Input Event Paint Event Window Event Key Event Mouse Event The AWT Event Hierarchy java.util ……. java.awt.event Programmer no need to worry about paint events Swing has more event types Programmer can create new event types

  13. The AWT Event Hierarchy 11 listener interfaces in java.awt.event ActionListener KeyListener AdjustmentListener MouseListener ComponentListener MouseMotionListener ContainerListener TextListener FocusListener WindowListener ItemListener

  14. The AWT Event Hierarchy • Semantic Events: What user does • ActionEvent (button click, menu selection) • AdjustmentEvent (adjusting scroll bar) • ItemEvent(selection from checkbox or list items) • TextEvent (the contents of a text field or text area were changed) • Additional events (likeMenuEvent, ChangeEvent) can be found injavax.swing.event. They are associated with Swing components and easy to handle. Will discuss some in the next topic.

  15. The AWT Event Hierarchy • Low-Level Events: facilitate semantic events • ComponentEvent (component resized, moved, shown, or hidden) • (A component is a user interface elements such as button, text field, scrollbar, panel, frame) • ComponentEvent is the ancestor of all low-level event classes • FocusEvent(component get focus) • ContainerEvent(a component has been added or removed. Programmers no need to worry about it)(A container is a screen area or component that can contain components. E.g. window, panel)

  16. The AWT Event Hierarchy • Low-Level Events: facilitates semantic events • KeyEvent (key pressed or released) • MouseEvent(mouse button pressed, released, moved, or dragged) • WindowEvent(window activated, deactivated, iconified, deiconified, or closed) • Will discuss KeyEvent and MouseEvent

  17. Last Time • AWT event delegation model • Event source: • What are inside an event class? • How to find out the types of events that a component generates? • Listener: • What are inside an listener class?

  18. Creating a Responsive GUI • Set up GUI • Layout various components on the contenPane of top-level container • Decide which events to handle • Begin with design objectives: Functionalities of GUI • For each component, find out the events that it generates • Check API of component class and look for methods addXXXXListener • implies that the component produces events of type XXXEvent • Handle events • Write listener class • Check API of listener interface and decide which methods to override • Check API of event class so as to get information about events • Create listener object • Register listener object with event source

  19. Objective and Outline • Objective: • Show how to write GUI programs that react to user actions. • Outline: • Java AWT event delegation model • An example • The AWT event hierarchy • Individual events • KeyEvents • MouseEvents • Special classes and interfaces for event handling • Adapter classes • The Action interface

  20. KeyEvent • Focus • A GUI consists of many components. • Which component received keystrokes? • The component that has focus • Focus is gained or lost in response to user actions: • A component gains focus if the user clicks the mouse inside it. • Or TAB/SHIT-TAB key can be used to traverses components which can receive input focus

  21. KeyEvent • Methods of java.awt.Component for managing focus • void requestFocus(): Moves focus to this component • boolean isFocusable(): Tells whether a component can be reached by using TAB or SHIFT-TAB • void transferFocus(): Transfer focus to the next component in the traversal order.

  22. KeyEvent • FocusEvent is generated when a component gains focus or loses focus. Refer to textbook for how to handle focus events.

  23. KeyEvent • Java distinguishes between characters and virtual key code • “A” and “a” have the same codeVK_A • There is noVK_a!! • More examples:VK_COMMA, VK_PERIOD,VK_OPEN_BRACKET, VK_SHIFT ...

  24. KeyEvent • KeyEvent objects are generated by the component with focus when a key is pressed or released. • Typing “a” generates three KeyEvent objects • 2 Lower-level events • keyPressed VK_A (Virtual key code) • keyReleased VK_A (Virtual key code) • One higher-level event: keyTyped “a” • Only for keys that generate character input • Methods of java.awt.event.KeyEvent Class: • getKeyCode() to get back virtual key code. • getKeyChar() to get back the key character • ….

  25. KeyEvent • Methods in the KeyListener Interface: • keyPressed(KeyEvent e) (what to do when VK_A pressed?) • keyReleased(KeyEvent e) (what to do when VK_A released?) • keyTyped(KeyEvent e) (what to do when “a” is typed?) e.getKeyCode() seems to give 0 within keyTyped Will illustrate with example

  26. KeyEvent • Example: Sketch.java • Move with either cursor keys or “h”, “j”, “k”, “l” keys • Move faster when SHIFT is pressed

  27. KeyEvent Setup: public SketchPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; // draw all lines for (int i = 0; i < lines.size(); i++) g2.draw((Line2D)lines.get(i)); } public void add(int dx, int dy) .. // add line segement last (x, y) –-- (x+dx, y+dy) // calls repaint() private ArrayList lines private Point2D last; // last point

  28. KeyEvent • Getting focus and register key listener public class SketchPanel { public SketchPanel() { … KeyHandler listener = new KeyHandler(); addKeyListener(listener); } public boolean isFocusable() { return true; } … } ..} We need this because by default a panel cannot get keyboard focus

  29. KeyEvent • Processing cursor keys: class KeyHandler implements KeyListener { public voidkeyPressed(KeyEvent event) { // set distance: whether shift is down int d; if (event.isShiftDown()) d = LARGE_INCREMENT; else d = SMALL_INCREMENT; // direction of move: what key is typed int keyCode = event.getKeyCode(); if (keyCode == KeyEvent.VK_LEFT) add(-d, 0); else if (keyCode == KeyEvent.VK_RIGHT) add(d, 0); else if (keyCode == KeyEvent.VK_UP) add(0, -d); else if (keyCode == KeyEvent.VK_DOWN) add(0, d); } Note: Can also use getModifiers of InputEventor getKeyModifiers of KeyEvent to find out whether SHIFT is down

  30. KeyEvent • Typing keys “h”. “j”, “k”, “l”: public void keyTyped(KeyEvent event) { char keyChar = event.getKeyChar(); int d; // distance of move if (Character.isUpperCase(keyChar)) { d = LARGE_INCREMENT; keyChar = Character.toLowerCase(keyChar); } else d = SMALL_INCREMENT; // direction of move if (keyChar == 'h') add(-d, 0); else if (keyChar == 'l') add(d, 0); else if (keyChar == 'k') add(0, -d); else if (keyChar == 'j') add(0, d); } Note: Can also use getModifiers of InputEvent or getKeyModifiers of KeyEvent to find out whether upper case or lower case

  31. Things to Try • Delete isFocusable() • getKeyCode within keyTyped • Modify example so that event source and listener are the same object • Make the listener class in Sketch.java an anonymous inner class.

  32. Objective and Outline • Objective: • Show how to write GUI programs that react to user actions. • Outline: • Java AWT event delegation model • An example • The AWT event hierarchy • Individual events • KeyEvents • MouseEvents • Special classes and interfaces for event handling • Adapter classes • The Action interface

  33. MouseEvent • Just want to know whether a button or menu is clicked? • No need to use mouse events explicitly. • Instead use ActionEvents generated by button or menu. • For drawing with mouse, mouse events are important.

  34. MouseEvent • MouseEventobjects generated by components where mouse cursor is located • Getting information about MouseEvents • int getX(), int getY() to get the x , y coordinates of mouse pointer. • Point getPoint() to get coordinates of mouse pointer as a Point object • int getClickCount() to get number of consecutive clicks. • int getModifiers() to find out, among other things, which mouse button is clicked.

  35. MouseEvent • Two listener interfaces • MouseListener • mousePressed(MouseEvent evt) • Invoked when a mouse button has been pressed on a component. • mouseReleased(MouseEvent evt) •   Invoked when a mouse button has been released on a component. • mouseClicked(MouseEvent evt) •  Invoked when the mouse button has been clicked (pressed and released) on a component. • mouseEntered(MouseEvent e)          Invoked when the mouse enters a component.  • mouseExited(MouseEvent e)          Invoked when the mouse exits a component.

  36. MouseEvent • MouseMotionListener • mouseMoved(MouseEvent evt) • API: Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed. • Actual: invoked frequently while mouse is moving • mouseDragged(MouseEvent evt) • API: Invoked when a mouse button is pressed on a component and then dragged. • Actual: invoked frequently while mouse is being dragged

  37. MouseEvent MouseTest.java -- place, move, and erase squares Setup: class MousePanelextends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; // draw all squares for (int i = 0; i < squares.size(); i++) g2.draw((Rectangle2D)squares.get(i)); } private static final int SIDELENGTH = 10; private ArrayList squares; private Rectangle2D current; … }

  38. MouseEvent MousePanel –Basic methods classMousePanel extends JPanel {… // Finds the first square containing a point. // Returns null when no square contains the point public Rectangle2D find(Point2D p){…} // Adds a square to collection public voidadd(Point2D p){…} // Removes a square to collection public voidremove(Point2D p){…} … }

  39. MouseEvent MousePanel generates MouseEvents, which will be handled by MouseHandler and MouseMotionHandler classMousePanelextends JPanel { … public MousePanel() { squares = new ArrayList(); current = null; addMouseListener(new MouseHandler()); addMouseMotionListener( new MouseMotionHandler()); } … }

  40. MouseEvent MouseHandler is an inner class of MousePanel classMousePanelextends Jpanel { private class MouseHandlerimplements MouseListener { public void mousePressed(MouseEvent event) { // add a new square if the cursor isn't inside a square current = find(event.getPoint()); if (current == null) add(event.getPoint()); } public void mouseClicked(MouseEvent event) { // remove the current square if double clicked current = find(event.getPoint()); if (current != null && event.getClickCount() >= 2) remove(current); …

  41. A side note: Adapter classes class MouseHandlerimplements MouseListener { public void mousePressed(MouseEvent event) { ..} public void mouseClicked(MouseEvent event) {..} } • not needed • mouseReleased(MouseEvent evt) • mouseEntered(MouseEvent e) • mouseExited(MouseEvent e) • But we have to implement it anyway class MouseHandlerimplements MouseListener { public void mousePressed(MouseEvent event) { ..} public void mouseClicked(MouseEvent event) {..} public void mouse Released(MouseEvent event) {} // does nothing. No code Public void mouseEntered(MouseEvent e){} Public void mouseExited(MouseEvent e){} }

  42. A side note: Adapter classes • Adaptor classes are introduced to save us from the trouble of providing empty methods • Example: • MouseAdapter is a class that consists of default implementation (do nothing) of all the three methods in MouseListener • Hence, the following is fine class MouseHandlerextends MouseAdapter { public void mousePressed(MouseEvent event) { ..} public void mouseClicked(MouseEvent event) {..} } • No compiler error even though mouseReleased, mouseEntered, and mouseExited are not provided. • MouseHandler objects are MousListeners. • Most listener interfaces have adapter classes

  43. MouseEvent Using adapter class, we now have: classMousePanelextends Jpanel { private class MouseHandlerextends MouseAdapter { public void mousePressed(MouseEvent event) { // add a new square if the cursor isn't inside a square current = find(event.getPoint()); if (current == null) add(event.getPoint()); } public void mouseClicked(MouseEvent event) { // remove the current square if double clicked current = find(event.getPoint()); if (current != null && event.getClickCount() >= 2) remove(current); …

  44. MouseEvent MouseMotionHandler is also an inner class of MousePanel class MousePanel extends Jpanel { private class MouseMotionHandler implements MouseMotionListener { public void mouseMoved(MouseEvent event){…} public void mouseDragged(MouseEvent event) { if (current != null) { int x = event.getX(); int y = event.getY(); // drag the rectangle to center it at (x, y) current.setFrame(x - SIDELENGTH/2, y - SIDELENGTH/2, SIDELENGTH, SIDELENGTH); repaint(); } }

  45. Objective and Outline • Objective: • Show how to write GUI programs that react to user actions. • Outline: • Java AWT event delegation model • An example • The AWT event hierarchy • Individual events • KeyEvents • MouseEvents • Special classes and interfaces for event handling • Adapter classes • The Action interface

  46. The Action Interface • Run ActionTest.java • One can change background color by doing one of the following: • Click on one of the buttons • Press a key : ctrl B = blue, ctrl Y = Yellow, ctrl R = red

  47. The Action Interface How to write the program? Do set up first class ActionPanel extends JPanel { public ActionPanel() { // add buttons for these actions add(new JButton(“Red”)); add(new JButton(“Blue”)); add(new JButton(“Yellow”)); } public void actionPerformed(ActionEvent event) { setBackground(…); repaint(); } }

  48. The Action Interface • How to handle events? • Need a class to listen for ActionEvent from button Class Listener1 implements ActionListener { public void actionPerformed (ActionEvent e) { // action codes: change background colour } } • Also need a class to listen for KeyEvent from keystroke Class Listener2 implements KeyListener { public void keyPressed (ActionEvent e) { // action codes: change background colour } } Bad solution: “action codes” appear in two different places

  49. Action Class Object Action Codes The Action Interface • Better solution • Place “action codes” in one class, called action class • Associate objects of the action class to different event sources • This mechanism is provided in Swing, beyond the AWT event model. Event Source 1 Event Soure 2

  50. The Action Interface • Next • How to write action classes? • How to associate action objects with event sources?

More Related