event driven programming - wright
TRANSCRIPT
Event driven programmingEvent driven programming
Listeners, sources, and events
GUI programmingGUI programming
Asynchronous programing / event-based programmingEventsEvents– Keyboard– Mouse
Must respond to events in arbitrary orderSimplistic approach: make a class to extend a window object– Manage layout– Create menus– Application areas– Manage user interaction– Manage user interaction
114Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
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");JButton button = new JButton( Click me );contentPane.add(button);
frame.setSize(50,50); frame.setVisible(true);
What happens when we click the button?We need two things:
} // end method main
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
115Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
We’re interested in the user-takes-action-on-a-button event!
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
Hey, I care about h t h t ! The user clicked me!what happens to you!
I’m listeningThe user clicked me!Here are the details on the event!
Design/implement the “what to do” code as appropriateThen set up a relationship between the code and the event-generating object
116Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
object
The listener interfaceThe listener interface
An event source (like a Swing GUI button) creates an event object when the user does something that matters (like click the button)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 y p
event source to your code.Recall: interfaces are 100% pure abstract classes, you must write implementations for the methods declared in the interfacep
ActionListener <interface>actionPerformed (e : ActionEvent )
ItemListener <interface>h d ( )
Register: Add me to your List of listeners!
addActionListener(this)
itemStateChanged (e : ItemEvent )
KeyListener <interface>keyPressed (e : KeyEvent)keyReleased (e : KeyEvent)
listenerListOK. I’ll call you when I have an event!
actionPerformed(e)
117Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
keyTyped (e : KeyEvent)y
I’ll use the method name in the contract!
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 ();JFrame frame = new JFrame ();frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);JPanel contentPane = (JPanel) frame.getContentPane ();button = new JButton ("Click me");contentPane.add (button);button.addActionListener (this); // register as listenerframe.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} // d l dl
118Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
} // end class ButtonHandler
Event processing is Event processing is concurrentconcurrent
Multiple objects can produce eventsEach object can have multiple listenersj pCode can run in an arbitrary order, or even simultaneously!– More on this later!
To illustrate this we need to:– (1) create a GUI with multiple components (say two buttons)– (2) register multiple listeners
119Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
GUI Layouts: Multiple componentsGUI Layouts: Multiple components
GUI Layout in Java SWING is own topic By default, JFrame uses a “BorderLayout”
C NORTHy , y– 5 regions, specify one with 2-arg add– one component to each region
Components can be nested
WES
T EASTCENTER
Components can be nestedimport java.awt.*;import javax.swing.*;…
SOUTH
button = new JButton ("Click me");contentPane.add (BorderLayout.CENTER,button);button.addActionListener (this);
JButton exitButton = new JButton("Exit");JButton exitButton new JButton( Exit );contentPane.add (BorderLayout.SOUTH,exitButton);exitButton.addActionListener(this);
frame.setSize (300,300);
120Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
…
Registering/Handling two event sourcesRegistering/Handling two event sources
If you register both buttons, then how does the action handler code know which button caused the event?
…button = new JButton ("Click me");contentPane.add (BorderLayout.CENTER,button);
The event object has all sorts of useful information!button.addActionListener (this);
JButton exitButton = new JButton("Exit");contentPane.add (BorderLayout.SOUTH,exitButton);exitButton.addActionListener(this); …
information!
public void actionPerformed (ActionEvent event) {if (event.getSource() == button) {
numClicks++;button.setText ("I’ve been clicked " +
n mClicks + " times ")numClicks + " times. ");} else {
System.exit(0);}
} // end method actionPerformed
121Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
…
Nested classesNested classes
Most OO-languages allow you to nest object code structures– In Java, this is often referred to as an inner class,
Inner classes have access to all members (even private members) of the outer class
class Outer { i i l lclass Outer {private int x = 0;public void go() {
Inner inner = new Inner();inner.y = 3;
Using inner classes can greatly simplify registering multiple listeners.
h b hinner.go();} // end method go
class Inner {private int y = 0;
Each button can have:its own (inner) class that it registers as an action listener p ate t y 0;
public void go() {x = y;
} // end method go} // end nested class Inner
} // d l O t
handles only that button’s functionWith full access to outer class
122Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
} // end class Outermembers
Handling multiple event sources Handling multiple event sources using inner classesusing inner classesusing 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() );exitButton.addActionListener (new ExitListener() );…class ClickListener implements ActionListener {
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 {class ExitListener implements ActionListener {public void actionPerformed (ActionEvent event) {
System.exit (0);} // end method actionPerformed
} // end inner class ClickListener
123Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
…
ExamplesExamples
Add “Speed up” and “Slow down” buttons to our simple ball animation
Use the keyboard to move in a general frame w/o buttons
SWING Layout– Add a button to each region– Next multiple buttons in one panel in central region– Etc– JLabel– JLabel– JTextfield– JCheckbox
124Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
– JList
Example: Simple WindowsExample: Simple Windows--style GUIstyle GUI
Swing buttonsSwing 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 onchanges the color in the central panel on demand.
We need to know:
• How to add buttons
• How to create a menu
• How to respond to events
• button clicks and menu selections
H t t t t t t t t fi ld This is our goal!• How to output text to a text field This is our goal!
126Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
Example Goal
127Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
Create a red panel
import javax.swing.*;…// i i// panel for displaying colorJPanel colorPanel;JFrame frame;JPanel contentFrame;…// create the color panelcolorPanel = new JPanel();colorPanel.setBackground(Color.RED);
contentFrame.add(BorderLayout.CENTER,colorPanel);
…f tVi ibl (t )
Just a red panel…frame.setVisible(true);}
Time to do the layout!
128Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
Nesting JButtons in a JPanel
import javax.swing.*;…// panel for buttons// panel for buttonsprivate JPanel buttonPanel;private JButton redButton;private JButton greenButton;private JButton blueButton;private JButton, blueButton;…buttonPanel = new JPanel();redButton = new JButton("RED");blueButton = new JButton("BLUE");blueButton = new JButton("BLUE");greenButton = new JButton("GREEN");// next buttons in panel (Flow Layout!)buttonPanel.add(redButton);buttonPanel add(blueButton);
Button Layout completebuttonPanel.add(blueButton);buttonPanel.add(greenButton);// add button panel to Layoutadd(buttonPanel,BorderLayout.SOUTH);
No functionality
129Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
…
Creating a Menu
import javax.swing.*;…
//JMenuBar menubar; // menu barJMenu colorMenu; // dropdown listJMenuItem redMenuItem; // menu itemsJMenuItem greenMenuItem;
blJMenuItem blueMenuItem;
…menubar = new JMenuBar(); l ("C l ")colorMenu = new JMenu("Color");
redMenuItem = new JMenuItem("Red");colorMenu.add(redMenuItem);… // repeat for each color
b dd( l M )
Layout nearly completemenubar.add(colorMenu);frame.setJMenuBar(menubar);…
No functionality
130Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
Using JLabel and JTextField
import javax.swing.*;…JTextField colorName;JTextField colorName;JPanel colorNamePanel;public ColorWindow() {…colorNamePanel = new JPanel();colorNamePanel = new JPanel();Jlabel colorLabel = new Jlabel("Current color:“));colorNamePanel.add(colorLabel);
colorName = new JTextField(5);//5char widecolorName.setEditable(false); // read onlycolorName.setText("Red");colorNamePanel add(colorName);
Layout completecolorNamePanel.add(colorName);
// add to Layoutadd(colorNamePanel,BorderLayout.NORTH);
No functionality
131Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
…
Inner class implements ActionListener
Recall: A listener can be implemented using an inner class, implementing the ActionListener interface– An inner class is encapsulated within a
larger class
Public Class ColorWindow
Cl Li t– An inner class may only be used within the larger class
– There can be several inner classes inside a
Class Listener (implements
ActionListener interface)
outer class)
132Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
Implementing the Listener
class Listener implements ActionListener {public void actionPerformed(ActionEvent e){
// find source of event and respond accordinglyif( (e.getSource() == redButton) ||
(e.getSource() == redMenuItem) ) {l l k d( l )colorPanel.setBackground(Color.RED);
colorName.setText("Red");}// repeat for blue and green colors
}}}
All listeners must implement the actionPerformed(ActionEvent e) method p ( )defined in the ActionListener interface.
This would work… can we do better?
133Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
Register the listener
The listener must be registered with any buttons
import javax.swing.*;… //and menu items that use the
listener.If desired, you can
// repeat for each color:
// register the menu itemredMenuItem.addActionListener(new i ())implement different
listeners with different GUI components.
Listener());
// register the buttonredButton.addActionListener(new i ())When registering an
ActionListener, create a new instance of the Li l
Listener());…
An elegant way to implement listeners is toListener class.– Repeat for each button
and menu item
An elegant way to implement listeners is toextend the JObjects and implement the interfacein the extended objects!
134Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
Example 2: a KeyboardExample 2: a Keyboard--based “game”based “game”
The basic form of a games is pretty
import java.awt.*;import javax.swing.*;public class GameFrame { games is pretty
standard– Make a JFrame
Make a JPanel
public GameFrame() {play();
} // end constructorprivate void pause(int millis) {
try { – Make a JPanelmove()paintComponent()
– Have an animation
try {Thread.sleep(millis);
} catch (Exception e) {e.printStackTrace();
} Have an animation loop
force movecheck game logic
} // method pause… // needs play()} // end class GameFrame
g gforce repaintpause/repeat
– Process inputs
public class Main {public static void main(String[] args) {
GameFrame game = new GameFrame();} // end method main
} // end class Main
135Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
} // end class Main
Main loop skeletonMain loop skeleton
…private void play() {
JF f JF (”CS241 G ")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 addKe Listener(panel)frame.addKeyListener(panel);frame.setSize(1024,600);frame.setVisible(true);while (true) {
pause(5);pause(5);panel.move();panel.repaint();
}} // end method play} // end method play…
136Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
Code for simple animationCode for simple animation
import java.awt.*;import java.awt.event.*;import javax swing *;
… public void move() {if (x > getWidth()-size) {import javax.swing. ;
public class GamePanel extends JPanel {int x; int y; int speed; int size; Image image;public GamePanel(int size, int speed) {
if (x > getWidth() size) { x = getWidth()-size;
}if (x < 0) { x = 0;
this.size = size;this.speed = speed;image = new ImageIcon("ship.gif").getImage();
} // end constructorpublic void paintComponent(Graphics g) {
}if (y > getHeight()-size) {y = getHeight()-size;}
if (y < 0) { y = 0;public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);g.fillRect(0,0,getWidth(),getHeight());g.setColor(Color.RED);//g.fillOval(x,y,ballSize,ballSize);
d I (i thi )
y 0; }// add update x/y
} // end method move…
g.drawImage(image,x,y,this);//System.out.println("(" + x + "," + y + ")");
} // end method paintComponent// code for move()
} // end class GamePanel
137Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
Keyboard eventsKeyboard events
…public class GamePanel extends JPanel implements KeyListener {
… public void move() {if (left) { x -= speed; }
boolean left = false;boolean right = false;boolean up = false;boolean down = false;
if (left) { x = speed; }if (right) { x += speed; }if (up) { y -= speed; }if (down) { y += speed; }
… public void keyPressed(KeyEvent e) {if (e.getKeyCode() == e.VK_LEFT) {left = true; }if (e.getKeyCode() == e.VK_RIGHT) {right = true;}if (e.getKeyCode() == e.VK_UP) {up = true;}
if (x > getWidth()-size) { x = getWidth()-size;
}if (x < 0) { x = 0;
if (e.getKeyCode() == e.VK_DOWN) {down = true;}} // end method keyPressed
public void keyReleased(KeyEvent e) {if (e.getKeyCode() == e.VK LEFT) {left = false;}
x 0;}if (y > getHeight()-size)
{y = getHeight()-size;}
if ( < 0) {if (e.getKeyCode() e.VK_LEFT) {left false;}if (e.getKeyCode() == e.VK_RIGHT){right = false;}if (e.getKeyCode() == e.VK_UP) {up = false;}if (e.getKeyCode() == e.VK_DOWN) {down = false;}} // end method keyReleased
if (y < 0) { y = 0;
}} // end method move…
138Wright State University, College of EngineeringDr. T. Doom, Computer Science & Engineering
CS 241Computer Programming II
…