Computer Science 15-110, Spring 2010
Class Notes:  Getting Started with Events


  1. timerFired Events
    1. Beeping (using JComponentWithEvents)
    2. Animation (with an instance variable)
    3. Smoother Animation (with setTimerDelay in start method)
  2. mousePressed Events
  3. keyPressed Events
  4. Helpful Patterns
    1. Pausing
    2. Simulating TimerFired Events While Paused
  5. Unhelpful Anti-Patterns
    1. Do Not Set Instance Variables in Paint Methods!
  6. Practice
  7. Coming soon...

Getting Started with Events

  1. timerFired Events
     
    1. Beeping (using JComponentWithEvents)
      // BeepingDemo.java
      // Demonstrates the timerFired event in JComponentWithEvents.
      // To compile and run this Java file, you must:
      // 1. Download current JComponentsWithEvents.class file from here:
      //       http://www.kosbie.net/cmu/JComponentWithEvents/
      //    and place it in the same directory as your Java program.
      // 2. Include a main method that calls the "launch" method
      //    defined in JComponentWithEvents (see below).
      import javax.swing.*;
      import java.awt.*;
      class BeepingDemo extends JComponentWithEvents {
      
        // This method is called at regular intervals by the timer.
        public void timerFired()  {
          beep();
        }
        public void paint(Graphics2D page) {
          page.fillRect(50, 50, 50, 50);
        }
        // Standard main method:
        public static void main(String[] args) { launch(500, 400); }
      }
    2. Animation (with an instance variable)
      // AnimationDemo.java
      // Demonstrates the timerFired event in JComponentWithEvents,
      // and using an instance variable to retain data between method calls
      // (to the event handlers and the paint method).
      import javax.swing.*;
      import java.awt.*;
      class AnimationDemo extends JComponentWithEvents {
        // this instance variable persists between method calls!
        private int rectX = 50;
        public void timerFired()  {
          rectX += 5;
        }
        public void paint(Graphics2D page) {
          page.fillRect(rectX, 50, 50, 50);
        }
        // Standard main method:
        public static void main(String[] args) { launch(500, 400); }
      }
    3. Smoother Animation (with setTimerDelay in start method)
        // Add this method to your Animation program
        // This method is called exactly once at the start of the program.
        public void start() {
          int delayInMilliseconds = 1;
          setTimerDelay(delayInMilliseconds);
        }
  2. mousePressed Events
    // MousePressedDemo.java
    // Demonstrates the mousePressed event in JComponentWithEvents.
    import javax.swing.*;
    import java.awt.*;
    class MousePressedDemo extends JComponentWithEvents {
      // these instance variables persists between method calls!
      private int rectX = 50;
      private int rectY = 50;
      // This method is called each time the mouse is pressed.
      // The parameters contain the (x,y) location of the mouse press.
      public void mousePressed(int x, int y) {
        rectX = x;
        rectY = y;
      }
      public void paint(Graphics2D page) {
        page.fillRect(rectX, rectY, 50, 50);
      }
      // Standard main method:
      public static void main(String[] args) { launch(500, 400); }
    }
  3. keyPressed Events
    // KeyPressedDemo.java
    // Demonstrates the mousePressed event in JComponentWithEvents.
    import javax.swing.*;
    import java.awt.*;
    class KeyPressedDemo extends JComponentWithEvents {
      // these instance variables persists between method calls!
      private int rectX = 50;
      private int rectY = 50;
      // This method is called each time a key is pressed.
      // The parameter contains the key that was pressed.
      // Note that you can use the constants UP, DOWN, LEFT, and RIGHT
      // to represent the arrow keys.
      public void keyPressed(char key) {
        if (key == RIGHT)
          rectX += 10;
        else if (key == 'l')
          // We'll take 'l' to mean "left" edge of the window
          rectX = 0;
      }
      public void paint(Graphics2D page) {
        page.fillRect(rectX, rectY, 50, 50);
      }
      // Standard main method:
      public static void main(String[] args) { launch(500, 400); }
    }
  4. Helpful Patterns
     
    1. Pausing
      // This demo shows how to pause and unpause an
      // animation using the 'p' key
      
      import javax.swing.*;
      import java.awt.*;
      
      class PausingDemo extends JComponentWithEvents {
      
        private boolean isPaused = false;
        private int counter = 0;
      
        public void timerFired() {
          if (isPaused == true)
            // if we are paused, do nothing, just return immediately!
            return;
          beep();
          counter++;
        }
        
        public void keyPressed(char key) {
          if (key == 'p')
            // turn on or off pausing with the 'p' key
            isPaused = !isPaused;
        }
      
        public void paint(Graphics2D page) {
          page.setFont(new Font("Arial", Font.BOLD, 16));
          page.drawString("Pause/unpause beeping with 'p' key", 50, 50);
          page.drawString("Calls to timerFired: " + counter, 50, 100);
        }
      
        public static void main(String[] args) { launch(400, 150);}
      }
    2. Simulating TimerFired Events While Paused
      // This demo shows how to simulate timer events
      // using the 't' key while an animation is paused
      // (using the 'p' key to pause and unpause).
      // This is VERY helpful for debugging!
      
      // To fully understand this code, compare it to the
      // previous example.  In particular, be sure to understand
      // why we wrote the onTimerFired helper method.
      
      import javax.swing.*;
      import java.awt.*;
      
      class SimulatedTimerEventsDemo extends JComponentWithEvents {
      
        private boolean isPaused = false;
        private int counter = 0;
        
        // This helper method is called by timerFired when it is not
        // paused, and also by keyPressed to simulate a timerEvent.
        public void onTimerFired() {
          beep();
          counter++;
        }
      
        public void timerFired() {
          if (isPaused == true)
            // if we are paused, do nothing, just return immediately!
            return;
          onTimerFired();
        }
        
        public void keyPressed(char key) {
          if (key == 'p')
            // turn on or off pausing with the 'p' key
            isPaused = !isPaused;
          else if (key == 't')
            // simulate a timer fired event when user presses 't'
            onTimerFired();
        }
      
        public void paint(Graphics2D page) {
          page.setFont(new Font("Arial", Font.BOLD, 16));
          page.drawString("Pause/unpause beeping with 'p' key", 50, 50);
          page.drawString("Paused = " + isPaused, 50, 100);
          page.drawString("Calls to timerFired: " + counter, 50, 150);
        }
      
        public static void main(String[] args) { launch(400, 200);}
      }
  5. Unhelpful Anti-Patterns
     
    1. Do Not Set Instance Variables in Paint Methods!

      This Program:
      import javax.swing.*;
      import java.awt.*;
      
      class MyGraphics extends JComponentWithEvents {
      
        private int rectX = 0;
        
        public void timerFired() {
          rectX += 30;
        }
        
        public void paint(Graphics2D page) {
          // This is meant to "wraparound" the rectangle.
          // The code is correct, but it's in the wrong place.
          // It belongs in the timerFired method, not here!!!
          if (rectX > getWidth()-200)
            rectX = 0;  // this line, in particular, is the problem!
          page.fillRect(rectX, 50, 200, 50);
        }
      
        public static void main(String[] args) { launch(500, 300);}
      }

      Works briefly, then generates this output:


      Rules:
        * Paint methods only GET instance variables.
        * Event handlers (timerFired, keyPressed, mousePressed) can GET OR SET instance variables.
       

  6. Practice
    See EventsPractice.html
     
  7. Coming soon...
    EventsDemo.html
     

carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem