L7_white by twittersubzero

VIEWS: 3 PAGES: 17

More Info
									                Lecture 7


Event-Driven Programming &
          Graphics

                                          1




  Event-Driven Programming
• Procedural programming is executed in
  procedural order.

• In event-driven programming, code is
  executed upon activation of events.




                                          2
                                   Events
  • An event can be defined as a type of
    signal to the program that something has
    happened.

  • The event is generated by external user
    actions such as mouse movements,
    mouse button clicks, and keystrokes, or by
    the operating system, such as a timer.


                                                                              3




                       Event Classes
                                     ActionEvent     ContainerEvent

                                   AdjustmentEvent    FocusEvent      MouseEvent

EventObject   AWTEvent             ComponentEvent      InputEvent

                                      ItemEvent        PaintEvent      KeyEvent

                                      TextEvent      WindowEvent


              ListSelectionEvent




                                                                              4
                 Event Information
An event object contains whatever properties
are pertinent to the event. You can identify the
source object of the event using the
getSource() instance method in the
EventObject class.
The subclasses of EventObject deal with
special types of events, such as button
actions, window events, component events,
mouse movements, and keystrokes.
                                                                 5




            Selected User Actions
                                  Source           Event Type
 User Action                      Object           Generated
 Clicked on a button              JButton          ActionEvent
 Changed text                     JTextComponent   TextEvent
 Double-clicked on a list item    JList            ActionEvent
 Selected or deselected an item   JList            ItemEvent
 with a single click
 Selected or deselected an item   JComboBox        ItemEvent




                                                                 6
                  The Delegation Model
                                                    EventObject
                    User
                   action
                                       Generate                   Notify listener
                                       an event

         Trigger an event

                            Source Object                           Listener Object
                              Register a listener object                    Event Handler




                                                                                            7




                 The Delegation Model:
                       Example

JButton jbt = new JButton("OK");
ActionListener listener = new OKListener();

//register the listener object by the source obj. jbt

jbt.addActionListener(listener);

So, when you click the button, the JButton object fires an ActionEvent and
passes it to invoke the listener's actionPerformed method to handle the
event.
                                                                                            8
                Selected Event Handlers
    Event Class         Listener Interface       Listener Methods (Handlers)
    ActionEvent         ActionListener           actionPerformed(ActionEvent)
    ItemEvent           ItemListener             itemStateChanged(ItemEvent)
    WindowEvent         WindowListener           windowClosing(WindowEvent)
                                                 windowOpened(WindowEvent)
                                                 windowIconified(WindowEvent)
                                                 windowDeiconified(WindowEvent)
                                                 windowClosed(WindowEvent)
                                                 windowActivated(WindowEvent)
                                                 windowDeactivated(WindowEvent)
    ContainerEvent      ContainerListener        componentAdded(ContainerEvent)
                                                 componentRemoved(ContainerEvent)




                                                                                             9




            java.awt.event.ActionEvent
      java.util.EventObject
+getSource(): Object             Returns the object on which the event initially occurred.

                                             This method is overridden in ActionEvent
  java.awt.event.AWTEvent

  java.awt.event.ActionEvent
+getActionCommand(): String       Returns the command string associated with this action. For a
                                   button, its text is the command string.
+getModifiers(): int              Returns the modifier keys held down during this action event.
+getWhen(): long                  Returns the timestamp when this event occurred. The time is
                                   the number of milliseconds since January 1, 1970, 00:00:00
                                   GMT.


                                                                                             10
          Simple Example
• The example displays a button in a frame.
  A message is displayed on the console
  when a button is clicked.




                                          11




                                          12
      Inner Class Listeners
A listener class is designed specifically
to create a listener object for a GUI
component (e.g., a button). It will not
be shared by other applications. So, it
is appropriate to define the listener
class inside the frame class as an
inner class.

                                           13




    What are Inner Classes?
Inner class: A class which is a member
  of another class.
Advantages: make programs simple for
 some applications.
• An inner class can reference the data
  and methods defined in the outer
  class in which it nests, so you do not
  need to pass the reference of the
  outer class to the constructor of the
                                           14
  inner class.
                   Inner Classes, cont.
public class Test {     // OuterClass.java: inner class demo
  ...                   public class OuterClass {
}                         private int data;

public class A {            /** A method in the outer class */
  ...                       public void m() {
}                             // Do something
                            }
          (a)
                            // An inner class
                            class InnerClass {
public class Test {           /** A method in the inner class */
  ...                         public void mi() {
                                // Directly reference data and method
    // Inner class              // defined in its outer class
    public class A {            data++;
      ...                       m();
    }                         }
}                           }
                        }
          (b)
                                               (c)

                                                                   15




                Inner Classes (cont.)
     • An inner class supports the work of its
       containing outer class and is compiled
       into a class named
       OuterClassName$InnerClassName.class.

     • For example, the inner class XClass in
       the outer class YClass is compiled
       into YClass$XClass.class.


                                                                   16
      Inner Classes (cont.)
• An inner class can be declared public,
  protected, or private subject to the
  same visibility rules applied to a
  member of the class.
• An inner class can be declared static.
  A static inner class can be accessed
  using the outer class name. A static
  inner class cannot access nonstatic
  members of the outer class
                                           17




 Revising SimpleEventDemo
    Using Inner Classes




                                           18
                                           19




     Handling Simple Action
            Events

• Objective: Display two buttons OK and
  Cancel in the window. When a button is
  clicked, a message is displayed on the
  console to indicate which button is clicked.

     TestActionEvent



                                           20
        The Graphics Class
The Graphics class is an abstract class
 for displaying figures and images on the
 screen on different platforms.

• You can draw strings, lines, rectangles,
  ovals, arcs, polygons, and polylines, using
  the methods in the Graphics class

                                            21




                                            22
                   Drawing on Panels
    JPanel can be used to draw graphics (including text)
   and enable user interaction.

   To draw in a panel, you create a new class that extends
   JPanel and override the paintComponent method to tell
   the panel how to draw things. You can then display
   strings, draw geometric shapes, and view images on the
   panel.
   •The JVM invokes paintComponent to draw things
   on a component. The user should never invoke
   paintComponent directly.
                                                                           23




             Drawing on Panels, cont.
public class DrawMessage extends JPanel {
  public static void main(String[] args) {
    JFrame frame = new JFrame("DrawMessage");
    frame. add(new DrawMessage()); /*creates & adds a panel obj*/
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 200);
    frame.setVisible(true);         JVM auto pass a Graphics obj to this method
  }
  /** Paint the message */
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawString("Welcome to Java!", 40, 40);
  }
}                                                                           24
       Drawing on Panels, cont.

                        (0, 0)    x        (x, 0)




                          y




                        (0, y)             (x, y)




                                                    25




                    NOTE
The Graphics class is an abstract class for
displaying figures and images on the screen on
different platforms.

Invoking super.paintComponent(g) is necessary to
ensure that the viewing area is cleared before a
new drawing is displayed.

To draw things, normally you create a subclass of
JPanel and override its paintComponent method
to tell the system how to draw. In fact, you can
draw things on any GUI component.
                                                    26
           Drawing Lines
   drawLine(x1, y1, x2, y2);

           (x1 , y1)




                           (x2 , y2)




                                       27




   Drawing Rectangles
• drawRect(x, y, w, h);
• fillRect(x, y, w, h);
    (x , y )



                           h



                       w




                                       28
Drawing Rounded Rectangles
• drawRoundRect(x, y, w, h, aw, ah);
• fillRoundRect(x, y, w, h, aw, ah);

      (x , y)
                         a h /2

                 aw /2

                                              h




                                      w


                                                  29




                Drawing Ovals
  • drawOval(x, y, w, h);
  • fillOval(x, y, w, h);

        (x, y)



                                          h



                                  w

                                                  30
                 Drawing Arcs
• drawArc(x, y, w, h, angle1, angle2);
• fillArc(x, y, w, h, angle1, angle2);




                                                              31




          Drawing Polygons
   int[] x = {40, 70, 60, 45, 20};
   int[] y = {20, 40, 80, 45, 60};
   g.drawPolygon(x, y, x.length);
   g.fillPolygon(x, y, x.length);


        (x[0], y[0])
                                               (x[1], y[1])
                       (x[3], y[3])



      (x[4], y[4])
                                      (x[2], y[2])

                                                              32
             Example 10.6
            Drawing a Clock
• Objective: Use drawing and trigonometric
  methods to draw a clock showing the specified
  hour, minute, and second in a frame.

                                     DrawClock


                                    DisplayClock

                                        Run
                                                   33

								
To top