Event Driven Programming - Computer Programming II - Slides | CS 241, Study notes of Computer Science

Material Type: Notes; Professor: Doom; Class: Computer Programming II; Subject: Computer Science; University: Wright State University-Main Campus; Term: Winter 2010;

Typology: Study notes

Pre 2010

Uploaded on 08/19/2009

koofers-user-7xl-1
koofers-user-7xl-1 🇺🇸

5

(1)

10 documents

1 / 9

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
Event driven programmingEvent driven programming
Listeners, sources, and events
GUI programmingGUI programming
zAsynchronous programing / event-based programming
zEvents
Keyboard
Mouse
zMust respond to events in arbitrary order
z
Simplistic approach: make a class to extend a window object
114
Wright State University, College of Engineering
Dr. T. Doom, Computer Science & Engineering CS 241
Computer Programming II
z
Simplistic
approach:
make
a
class
to
extend
a
window
object
Manage layout
Create menus
Application areas
Manage user interaction
What is the role of an event?What is the role of an event?
import javax.swing.*;
public static void main (String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = (JPanel) frame.getContentPane();
JButton button = new JButton("Click me");
contentPane.add(button);
115
Wright State University, College of Engineering
Dr. T. Doom, Computer Science & Engineering CS 241
Computer Programming II
zWhat happens when we click the button?
zWe need two things:
A way to know when something happens (an event)
–A method to be called to perform the appropriate task in response
zWe’re interested in the user-takes-action-on-a-button event!
frame.setSize(50,50);
frame.setVisible(true);
} // end method main
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download Event Driven Programming - Computer Programming II - Slides | CS 241 and more Study notes Computer Science in PDF only on Docsity!

Event driven programmingEvent driven programming

Listeners, sources, and events

GUI programmingGUI programming

z Asynchronous programing / event-based programming

z Events

  • Keyboard
  • Mouse

z Must respond to events in arbitrary order

z Simplistic approach: make a class to extend a window object

Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

z Simplistic approach: make a class to extend a window object

  • Manage layout
  • Create menus
  • Application areas
  • Manage user interaction

What is the role of an event?What is the role of an event?

import javax.swing.*; … public static void main (String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel contentPane = (JPanel) frame.getContentPane();

JButton button = new JButton("Click me"); contentPane.add(button);

Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

z What happens when we click the button?

z We need two things:

  • A way to know when something happens (an event)
  • A method to be called to perform the appropriate task in response

z We’re interested in the user-takes-action-on-a-button event!

frame.setSize(50,50); frame.setVisible(true); } // end method main

Events have sources and handlers/listenersEvents have sources and handlers/listeners

private int numClicks = 0; … public void processButtonClick() { numClicks++;

button.setText("I’ve been clicked " + numClicks + " times. ");

} // end method processButtonClick

Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

z Design/implement the “what to do” code as appropriate

z Then set up a relationship between the code and the event-generating

object

Hey, I care about

what happens to you!

I’m listening

The user clicked me!

Here are the details on the event!

The listener interfaceThe listener interface

z An event source (like a Swing GUI button) creates an event object when

the user does something that matters (like click the button)

z Every event type has a matching listener interface

  • If your code implements a listener interface and registers as a listener
  • then you’ve set up a contract that allows communication from the

event source to your code.

R ll i f 100% b l i

Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

z Recall: interfaces are 100% pure abstract classes, you must write

implementations for the methods declared in the interface

ActionListener actionPerformed (e : ActionEvent )

ItemListener itemStateChanged (e : ItemEvent )

KeyListener keyPressed (e : KeyEvent) keyReleased (e : KeyEvent) keyTyped (e : KeyEvent)

listenerList

Register: Add me to your List of listeners!

OK. I’ll call you when I have an event!

I’ll use the method name in the contract!

addActionListener(this)

actionPerformed(e)

An eventAn event--handling listener object!handling listener object!

import javax.swing.; import java.awt.event.;

public class ButtonHandler implements ActionListener { private JButton button; private int numClicks = 0; public void buildGUI () { JFrame frame = new JFrame (); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); JPanel contentPane = (JPanel) frame.getContentPane ();

Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

( ) g (); button = new JButton ("Click me"); contentPane.add (button); button.addActionListener (this); // register as listener frame.setSize (300,300); frame.setVisible (true); } // end method GUI

public void actionPerformed (ActionEvent event) { numClicks++; button.setText ("I’ve been clicked " + numClicks + " times. "); } // end method actionPerformed } // end class ButtonHandler

Nested classesNested classes

z Most OO-languages allow you to nest object code structures

  • In Java, this is often referred to as an inner class

z Inner classes have access to all members (even private members) of the

outer class

class Outer { private int x = 0; public void go() {

z Using inner classes can greatly

simplify registering multiple

Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

p g Inner inner = new Inner(); inner.y = 3; inner.go(); } // end method go

class Inner { private int y = 0; public void go() { x = y; } // end method go } // end nested class Inner } // end class Outer

p y g g p

listeners.

z Each button can have:

z its own (inner) class that

z it registers as an action listener

z handles only that button’s

function

z With full access to outer class

members

Handling multiple event sourcesHandling multiple event sources

using inner classesusing inner classes

button = new JButton ("Click me"); contentPane.add (BorderLayout.CENTER,button); button.addActionListener ( new ClickListener() );

JButton exitButton = new JButton ("Exit"); contentPane.add (BorderLayout.SOUTH,exitButton); exitButton.addActionListener ( new ExitListener() ); … class ClickListener implements ActionListener {

Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

p { public void actionPerformed (ActionEvent event) { numClicks++; button .setText ("I’ve been clicked " + numClicks + " times. "); } // end method actionPerformed } // end inne class ClickListener

class ExitListener implements ActionListener { public void actionPerformed (ActionEvent event) { System.exit (0); } // end method actionPerformed } // end inner class ClickListener …

ExamplesExamples

z Add “Speed up” and “Slow down” buttons to our simple ball animation

z Use the keyboard to move in a general frame w/o buttons

z SWING Layout

Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

z SWING Layout

  • Add a button to each region
  • Next multiple buttons in one panel in central region
  • Etc
  • JLabel
  • JTextfield
  • JCheckbox
  • JList

Example: Simple WindowsExample: Simple Windows--style GUIstyle GUI

Swing buttons

Swing Menus

Responding to button click events

Creating a simple WindowsCreating a simple Windows--Style GUIStyle GUI

We will create a simple GUI application that

changes the color in the central panel on

demand.

We need to know:

  • How to add buttons

Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

  • How to create a menu
  • How to respond to events
    • button clicks and menu selections
  • How to output text to a text field

This is our goal!

Example Goal

Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

Using JLabel and JTextField

import javax.swing.*;

JTextField colorName;

JPanel colorNamePanel;

public ColorWindow() {

colorNamePanel = new JPanel();

Jlabel colorLabel = new Jlabel("Current

color:“));

Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

color: ));

colorNamePanel.add(colorLabel);

colorName = new JTextField(5);//5char wide

colorName.setEditable(false); // read only

colorName.setText("Red");

colorNamePanel.add(colorName);

// add to Layout

add(colorNamePanel,BorderLayout.NORTH);

Layout complete

No functionality

Inner class implements ActionListener

z Recall: A listener can be implemented using an

inner class, implementing the ActionListener

interface

  • An inner class is encapsulated within a

larger class

  • An inner class may only be used within the

larger class

Public Class

ColorWindow

Class Listener

(implements

Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

larger class

  • There can be several inner classes inside a

outer class

ActionListener

interface)

Implementing the Listener

class Listener implements ActionListener {

public void actionPerformed(ActionEvent e)

// find source of event and respond accordingly

if( (e.getSource() == redButton) ||

(e.getSource() == redMenuItem) ) {

colorPanel.setBackground(Color.RED);

colorName.setText("Red");

Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

// repeat for blue and green colors

All listeners must implement the actionPerformed(ActionEvent e) method

defined in the ActionListener interface.

This would work… can we do better?

Register the listener

z The listener must be

registered with any buttons

and menu items that use the

listener.

z If desired, you can

implement different

listeners with different GUI

import javax.swing.*;

// repeat for each color:

// register the menu item

redMenuItem.addActionListener(new

Listener());

// i h b

Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

listeners with different GUI

components.

z When registering an

ActionListener, create a

new instance of the

Listener class.

  • Repeat for each button

and menu item

// register the button

redButton.addActionListener(new

Listener());

An elegant way to implement listeners is to

extend the JObjects and implement the interface

in the extended objects!

Example 2: a KeyboardExample 2: a Keyboard--based “game”based “game”

z The basic form of a

games is pretty

standard

  • Make a JFrame
  • Make a JPanel

z move()

import java.awt.; import javax.swing.; public class GameFrame { public GameFrame() { play(); } // end constructor private void pause(int millis) { try { Thread.sleep(millis); } catch (Exception e) {

Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

z paintComponent()

  • Have an animation

loop

z force move

z check game logic

z force repaint

z pause/repeat

  • Process inputs

public class Main { public static void main(String[] args) { GameFrame game = new GameFrame(); } // end method main } // end class Main

} ( p ) { e.printStackTrace(); } } // method pause … // needs play() } // end class GameFrame

Main loop skeletonMain loop skeleton

private void play() {

JFrame frame = new JFrame(”CS241 Game");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

GamePanel panel = new GamePanel(40,4);

frame.getContentPane().add(BorderLayout.CENTER,panel);

frame.addKeyListener(panel);

frame.setSize(1024,600);

frame setVisible(true);

Wright State University, College of Engineering Dr. T. Doom, Computer Science & Engineering

CS 241 Computer Programming II

frame.setVisible(true);

while (true) {

pause(5);

panel.move();

panel.repaint();

} // end method play