paint
5-1
GUIs and Events
Rick Mercer
paint
5-2
Event-Driven Programmingwith Graphical user Interfaces
Most applications have graphical userinterfaces to respond to user desires
paint
5-3
A Few Graphical Components
A Graphical User Interface (GUI) presents agraphical view of an application to users.
To build a GUI application, you must:
Have a well-tested model that is independent of the view
Make graphical components visible to the user
Ensure the correct things happen for each event
user clicks button, moves mouse, presses enter key, ...
Let's first consider some of Java's GUI components:
windows, buttons, and text fields
paint
5-4
Classes in the swing package
The javax.swing package has componentsthat show in a graphical manner
     JFrame: window with title, border, menu, buttons
    JButton: A component that can "clicked"
    JLabel: A display area for a small amount of text
    JTextField:  Allows editing of a single line of text
paint
5-5
Get a window to show itself
Code to tell a JFrame to show itself:
   // Construct window with a title
   JFrame aWindow = new JFrame("Graffiti");
   // Make sure the program terminates when window closes
   aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   aWindow.setVisible(true);
paint
5-6
Some JFrame messages
Set the size of the window with
      aWindow.setSize(220, 100);
The first int is the width of the window in pixels
the second int is the height of the window in pixels
paint
5-7
Building components
So far we have an empty window
Let us add a button, a label, and an editable line
First construct three graphical components
 JButton clickMeButton =
    new JButton("Nobody is listening to me");
 JLabel aLabel =
    new JLabel("Button above, text field below");
 JTextField textEditor =
    new JTextField("You can edit this text ");
Next, add these objects to a window object
paint
5-8
Add components to a window
Add the previously constructed components to one ofthe five areas of a JFrame
    aWindow.add(clickMeButton, BorderLayout.NORTH);
    aWindow.add(aLabel, BorderLayout.CENTER);
    aWindow.add(textEditor, BorderLayout.SOUTH);
paint
5-9
The 5 areas of BorderLayout
By default, JFrame objects have only fiveplaces where you can add components
a 2nd add wipes out the 1st
There are many layout managers
We will use null for layout:
Must set the size and location of each component
paint
5-10
  Null layout manager  easier to layout components
We will explicitly state where eachcomponent goes on a Container, which canbe a JFrame or JPanel
Code Demo: Add these components to aGUI
JLabel, JButton, JTextField
paint
5-11
So what happens next?
You can layout a real pretty GUI
You can click on buttons, enter text into atext field, move the mouse, press a key
And NOTHING happens
So let’s make something happen…
paint
5-12
Java's Event Model
Java can let the operating system notifygraphical components of user interaction
JButton objects notified when user clicks it
JTextField objects with focus knows when theuser enters text and your program can respond
A menu item know that a user has selected it
Event driven programs respond to many things
mouse clicks, mouse movements
clicks on hyperlinks, buttons, menu items
Users pressing any key, selecting a list item, movinga slider bar, …
paint
5-13
Example: Action Events
The buttons, text fields, and menu items donot perform the actions
Instead JButton,  JTextFieldJMenuItemobjects send actionPerformed messages toother objects, for example
We write code to respond to the aboveevents in actionPerformed methods
This requires a class that implements theActionListener interface, for example
paint
5-14
Event Driven Program with GUIs
Key elements of an event-driven GUI
Graphical components
The screen elements that a user manipulates with the mouseand keyboard  JFrame JLabel JButton JScrollbarJMenuItem JTextField JTextArea JList ...
Layout managers
Govern how the components appear on the screen
Examples FlowLayout GridLayout  null layout
Events
Signal that a user interacted with the GUI
Examples: mouse clicks, keys pressed, hyperlink selected,time expires on a timer, …
paint
5-15
Java's Event Model
JFrame
JButton
1 LayoutGraphicalComponents
JFrame
JButton
JTextField
JMenuItem
Listener
3 You register objects that waits for messages from graphical components addActionListener
Listener
Listener
Users interactwith thesegraphicalcomponents
You write classesthat implement thecorrect interface
ActionListener
paint
5-16
A Java GUI: Rick's model
Preview for writing a GUI with events
1. Have a class that extends JFrame so your class IS-AJFrame. so you inherit many methods already working!
2. Add main to start up the GUI (could be separate file)
3. Add instance variables – include graphical componentsthat will be needed by two or more methods (aJTextField, Timer, or JList will be needed by listenerslater
4. Lay out a GUI and initialize instance variables in theconstructor
paint
5-17
The first 4 steps
import java.awt.*;import java.awt.*;
import javax.swing.*;import javax.swing.*;
public class SomeEvents extends JFrame {public class SomeEvents extends JFrame {
  public static void main(String[] args) {  public static void main(String[] args) {
    // Construct an instance of this class and show it    // Construct an instance of this class and show it
    SomeEvents window new SomeEvents();    SomeEvents window new SomeEvents();
    window.setVisible(true);    window.setVisible(true);
  }  }
  // graphical component to be "listened" to  // graphical component to be "listened" to
  private JButton aButton;  private JButton aButton;
  public SomeEvents() {  public SomeEvents() {
    layoutGUI();    layoutGUI();
  }  }
  private void layoutGUI();  private void layoutGUI();
    // Lay out the GUI, initialize instance variables    // Lay out the GUI, initialize instance variables
    // Have this object send some messages to itself    // Have this object send some messages to itself
    this.setSize(200, 100);    this.setSize(200, 100);
    this.setTitle("Listen to button");    this.setTitle("Listen to button");
  
paint
5-18
No one is "Listening"
Okay, now we have a GUI
but when run, nothing happens
Wanted: An object to listen to the button thatunderstands a specific message such as
actionPerformed
Also need to tell the button who it can send theactionPerfomed message to
Register the listener with this method
addActionListener(ActionListener al)
paint
5-19
Handling Events
5. Add a private inner class that can listen to theevent that the graphical component will generate
Your class must implement a listener interface to guarantee thatit has the expected methods: First up: ActionListener
6. Register the listener object to the GUI component(JButton JTextField) so it can later sendactionPerformed messages to that listener whenthe use clicks the button or presses enter.
events occur anytime in the future--the listener is listening(waiting for user generated events such as clicking abutton or entering text into a text field)
paint
5-20
ActionEvent / ActionListener
When a JButton object is clicked, it constructs anActionEvent object and sends it to theactionPerformed method of its listeners
We can usually ignore that parameter, other times we can't
To register a listener to a JButton, send anaddActionListener message to button
public void addActionListener(ActionListener al)public void addActionListener(ActionListener al)
You need an ActionListener object
But there is no ActionListener class!
What can we do?????
paint
5-21
Implement an interface
Then your object can be treated as if it were anActionListener
Polymorphism in action: We can have anynumber of actionPerformed methods thatdo whatever they are supposed to.  The Buttondoes not care what happened
paint
5-22
Inner class
Add an inner class
inner classes have access to the enclosingclasses' instance variables
Make it private since no one else needs toknow about it
Java added inner classes for the very exactpurpose: to have listener objects respond touser interactions with GUI components
paint
5-23
Have a class thatimplements ActionListener
  // 5. inner class to listen to events  // 5. inner class to listen to events
  private class ButtonListener implements ActionListener {  private class ButtonListener implements ActionListener {
    // No constructor needed here    // No constructor needed here
    // Must have this method to implement ActionListener    // Must have this method to implement ActionListener
   public void actionPerformed(ActionEvent anActionEvent){   public void actionPerformed(ActionEvent anActionEvent){
      System.out.println("Button was clicked.");      System.out.println("Button was clicked.");
   }   }
  // 6. Register the instance of the listener so the  // 6. Register the instance of the listener so the
  // component can later send messages to that object  // component can later send messages to that object
  ButtonListener aListener new ButtonListener();  ButtonListener aListener new ButtonListener();
  aButton.addActionListener(aListener);  aButton.addActionListener(aListener);
Caution: this is easy to forget. It is anerror no one will tell you about
paint
5-24
Polymorphism throughinterfaces
Can have many ActionListener objects
Any class that implements ActionListener
may need a different class for every button andtext field in the GUI
But they all can be treated as ActionListener objects
They can be passed as arguments to this method
public void addActionListener(ActionListener aL)
Adds the specified action listener to receive action events from JButtons,TextFields,  ...
Parameter: aL an instance of class that implements the ActionListenerinterface
paint
5-25
Assignment Compatible
Can pass instances of classes implementingan interface to the interface type parameter
addActionListener(ActionListener anyListener)
addActionListener(new ButtonListener());
   addActionListener(new TextFieldListener());
ButtonListener and TextFieldListenermust implement interface ActionListener
paint
5-26
Listen to JTextField
Add to the current GUI
Add a JTextField so when the user enters aString, show it in Upper case
Need JTextArea methods getText and setText
paint
5-27
JList
Code demo:
Show a JList GUI component with aListModel set as the model
List to clicks on the elements in the JList
Begin with code on the next slide
paint
5-28
public class ShowJListListModel extends JFrame {
  public static void main(String[] args) {
    JFrame window = new ShowJListListModel();
    window.setVisible(true);
  }
  private JList guiList;
  private ListModel allStrings;
  public ShowJListListModel() {
    setSize(380, 200);
    setLocation(100, 100);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // List must implement ListModel so it can be shown in a JList
    allStrings = new MyLittleList();
    guiList = new JList(allStrings);
    guiList.setFont(new Font("Arial", Font.BOLD, 13));
    this.getContentPane().add(guiList, BorderLayout.CENTER);
  }
}
paint
5-29
Demo javax.swing.Timer
Count down to 10
A timer is constructed and begun like this
  timer = new Timer(1000, new TimerListener());
  timer.start();
Timers need an ActionListener argument
private class TimerListener implements ActionListener {
  public void actionPerformed(ActionEvent ae) {
    // Do whatever is here when the timer sends
    // this listener an actionPerformed message
  }
}