JMU
Event-Driven Programming in GUIs
An Introduction with Examples in Java (Swing)


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Overview
The Focus of Event-Driven Design
Event Models
The Event Queue
Threads
Using a JButton javax.swing.JButton
Using a JButton javax.swing.JButton (cont.)

An Example Observer

javaexamples/usinggui/ButtonHandler.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * An example that uses buttons
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class ButtonHandler implements ActionListener
{
    private JLabel outputLabel;
    

    /**
     * Ecplicit Value Constructor.
     */
    public ButtonHandler(JLabel outputLabel)
    {
        this.outputLabel = outputLabel;
    }


    /**
     * Handle actionPerformed message (required by ActionListener)
     *
     * @param event   The ActionEvent that generatedt his message
     */
    public void actionPerformed(ActionEvent event)
    {
       String       command;
       
       command = event.getActionCommand();
       if (command.equals("No"))
       {
          outputLabel.setText("Don't disagree with me!");
       }
       else if (command.equals("Yes"))
       {
          outputLabel.setText("I really respect your opinion.");
       }
    }
    
}
        
Using a JButton javax.swing.JButton (cont.)

An Example Subject

javaexamples/usinggui/ButtonDriver.java
import java.awt.*;
import javax.swing.*;


/**
 * An example that uses a button
 *
 * @author  Prof. David Bernstein, James Madison Univeristy
 * @version 1.0
 */
public class ButtonDriver
{

    /**
     * The entry point of the example
     *
     * @param args   The command line arguments
     */
    public static void main(String[] args)
    {
        Container   contentPane;
        JButton     noButton, yesButton;
        JFrame      window;
        JLabel      titleLabel;


        window = new JFrame("A Really Amazing Window!");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        // Get the content pane
        contentPane = window.getContentPane();
        contentPane.setLayout(null);
        
        // Construct the widgets.components
        titleLabel = new JLabel("A Button Example");
        yesButton  = new JButton("Yes");
        noButton = new JButton("No");

        // Layout the content pane
        contentPane.add(titleLabel);
        titleLabel.setBounds(60,20,290,30);

        contentPane.add(yesButton);
        yesButton.setBounds(190,210,60,30);

        contentPane.add(noButton);
        noButton.setBounds(260,210,90,30);

        
        // Make a ButtonHandler object an ActionListener on the buttons
        ButtonHandler handler = new ButtonHandler(titleLabel);
        
        yesButton.addActionListener(handler);
        noButton.addActionListener(handler);

        window.setSize(400,400);
        window.setVisible(true);
    }
}
        
Using a JButton javax.swing.JButton (cont.)

A More Sophisticated Example

javaexamples/usinggui/AdvancedButtonDriver.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * An example that uses some "advanced" features of buttons.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class AdvancedButtonDriver
{
    
    /**
     * The entry point of the example
     *
     * @param args   The command line arguments
     */
    public static void main(String[] args)
    {
        Container   contentPane;
        JButton     noButton, yesButton;
        JFrame      window;
        JLabel      titleLabel;
        
        window = new JFrame("A Really Amazing Window!");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Get the content pane
        contentPane = window.getContentPane();
        contentPane.setLayout(null);

        // Construct the widgets.components
        titleLabel   = new JLabel("A Button Example");

        noButton     = new JButton("Non");
        noButton.setActionCommand("No");
        noButton.setMnemonic('N'); // There is also a setAccelerator() method.
   
       
        yesButton    = new JButton("Oui");
        yesButton.setActionCommand("Yes");
        yesButton.setMnemonic('O');
        
        // Layout the content pane
        contentPane.add(titleLabel);
        titleLabel.setBounds(60,20,290,30);

        contentPane.add(yesButton);
        yesButton.setBounds(190,210,60,30);
        
        contentPane.add(noButton);
        noButton.setBounds(260,210,90,30);
                
        // Make a ButtonHandler object an ActionListener on the buttons
        ButtonHandler handler = new ButtonHandler(titleLabel);
        
        yesButton.addActionListener(handler);
        noButton.addActionListener(handler);

        window.setSize(400,400);
        window.setVisible(true);
    }
}
        
Using a JCheckBox javax.swing.JCheckBox
Using a JCheckBox javax.swing.JCheckBox (cont.)

An Example Observer

javaexamples/usinggui/CheckBoxHandler.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * A frame that illustrates the use of checkboxes
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class CheckBoxHandler implements ActionListener, ItemListener
{
    private JTextArea displayArea;
    

    /**
     * Explicit Value Constructor.
     */
    public CheckBoxHandler(JTextArea displayArea)
    {
        this.displayArea = displayArea;
    }


    /**
     * Handle actionPerformed events (required by ActionListener)
     *
     * @param e   The event
     */
    public void actionPerformed(ActionEvent e)
    {
       // You could handle events generated by the
       // JCheckBox objects here
    }


    /**
     * Handle itemStateChanged events (required by ItemListener)
     *
     * @param e   The event
     */
    public void itemStateChanged(ItemEvent e)
    {
       int             state;
       JToggleButton   tb;


       tb = (JToggleButton)(e.getItem());
       state = e.getStateChange();

       if (tb.getActionCommand().equals("planesCB")) 
       {
          if (state == ItemEvent.SELECTED) 
          {
             displayArea.append("If you were meant to fly "+
                             "you'd have wings\n\n");
          }
          else if (state == ItemEvent.DESELECTED) 
          {
             displayArea.append("Afraid to fly???\n\n");
          }
       } 
       else if (tb.getActionCommand().equals("trainsCB")) 
       {
          if (state == ItemEvent.SELECTED) 
          {
             displayArea.append("Choo, Choo...\n\n");
          } 
          else if (state == ItemEvent.DESELECTED) 
          {
             displayArea.append("The little engine that couldn't!\n\n");
          }
       } 
       else if (tb.getActionCommand().equals("automobilesCB")) 
       {
          if (state == ItemEvent.SELECTED) 
          {
             displayArea.append("I drove a Geo Prizm in 1995!\n\n");
          } 
          else if (state == ItemEvent.DESELECTED) 
          {
             displayArea.append("I drive the same one today!\n\n");
          }
       }
    }
}
        
Using a JCheckBox javax.swing.JCheckBox (cont.)

An Example Subject

javaexamples/usinggui/CheckBoxDriver.java
import java.awt.*;
import javax.swing.*;

/**
 * An example that uses checkboxes
 *
 * @version 1.0
 * @author  Prof. David Bernstein, James Madison Univeristy
 */
public class CheckBoxDriver
{
    /**
     * The entry point of the example
     *
     * @param args   The command line arguments
     */
    public static void main(String[] args)
    {
        Container       contentPane;
        JCheckBox       automobilesCB, planesCB, trainsCB;
        JLabel          titleLabel;
        JPanel          south;
        JTextArea       textArea;
        JFrame          frame;

        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        contentPane = frame.getContentPane();

        contentPane.setLayout(new BorderLayout());

        titleLabel = new JLabel();
        titleLabel.setText("A CheckBox Example");
        contentPane.add(titleLabel, BorderLayout.NORTH);


        textArea = new JTextArea(40,20);
        contentPane.add(textArea, BorderLayout.CENTER);

        south = new JPanel();
        south.setLayout(new FlowLayout());
        contentPane.add(south, BorderLayout.SOUTH);       

        planesCB = new JCheckBox("Planes");
        planesCB.setActionCommand("planesCB");
        planesCB.setMnemonic('P');
        south.add(planesCB, BorderLayout.WEST);

        trainsCB = new JCheckBox("Trains");
        trainsCB.setActionCommand("trainsCB");
        trainsCB.setMnemonic('T');
        south.add(trainsCB, BorderLayout.EAST);

        automobilesCB = new JCheckBox("Automobiles");
        automobilesCB.setActionCommand("automobilesCB");
        automobilesCB.setMnemonic('A');
        south.add(automobilesCB, BorderLayout.SOUTH);

        // Setup the observer
        CheckBoxHandler handler = new CheckBoxHandler(textArea);
        planesCB.addItemListener(handler);
        trainsCB.addItemListener(handler);
        automobilesCB.addItemListener(handler);
        
        
        frame.setSize(400,400);
        frame.setVisible(true);
    }
}
        
Using a JRadioButton javax.swing.JRadioButton
Using a JRadioButton javax.swing.JRadioButton (cont.)

An Example Subject

javaexamples/usinggui/RadioButtonDriver.java
import java.awt.*;
import javax.swing.*;

/**
 * An example that uses checkboxes
 *
 * @version 1.0
 * @author  Prof. David Bernstein, James Madison Univeristy
 */
public class RadioButtonDriver
{
    /**
     * The entry point of the example
     *
     * @param args   The command line arguments
     */
    public static void main(String[] args)
    {
        Container       contentPane;
        JCheckBox       automobilesCB, planesCB, trainsCB;
        JLabel          titleLabel;
        JPanel          south;
        JTextArea       textArea;
        JFrame          frame;

        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        contentPane = frame.getContentPane();

        contentPane.setLayout(new BorderLayout());

        titleLabel = new JLabel();
        titleLabel.setText("A CheckBox Example");
        contentPane.add(titleLabel, BorderLayout.NORTH);


        textArea = new JTextArea(40,20);
        contentPane.add(textArea, BorderLayout.CENTER);

        south = new JPanel();
        south.setLayout(new FlowLayout());
        contentPane.add(south, BorderLayout.SOUTH);       

        planesCB = new JCheckBox("Planes");
        planesCB.setActionCommand("planesCB");
        planesCB.setMnemonic('P');
        south.add(planesCB, BorderLayout.WEST);

        trainsCB = new JCheckBox("Trains");
        trainsCB.setActionCommand("trainsCB");
        trainsCB.setMnemonic('T');
        south.add(trainsCB, BorderLayout.EAST);

        automobilesCB = new JCheckBox("Automobiles");
        automobilesCB.setActionCommand("automobilesCB");
        automobilesCB.setMnemonic('A');
        south.add(automobilesCB, BorderLayout.SOUTH);

        // Setup the observer
        CheckBoxHandler handler = new CheckBoxHandler(textArea);
        planesCB.addItemListener(handler);
        trainsCB.addItemListener(handler);
        automobilesCB.addItemListener(handler);
        
        // This is new
        // Setup the button group
        // This is different
        ButtonGroup group = new ButtonGroup();
        group.add(planesCB);
        group.add(trainsCB);
        group.add(automobilesCB);

        
        frame.setSize(400,400);
        frame.setVisible(true);
    }
}
        
Using a Text Component
Using a Text Component (cont.)

An Example Observer

javaexamples/usinggui/TextFieldHandler.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;


/**
 * An example of a DocumentListener.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class TextFieldHandler implements DocumentListener
{
    /**
     * Default constructor
     */
    public TextFieldHandler()
    {
    }

    /**
     * Handle changedUpdate events (required by DocumentListener)
     *
     * @param e   The event
     */
    public void changedUpdate(DocumentEvent e)
    {
        Document    source;

        source = e.getDocument();

        try 
        {
            System.out.println("In changeUpdate:\n"+
                          source.getText(0,source.getLength())+
                          "\n\n");
        } 
        catch (BadLocationException ble) 
        {
            // Shouldn't get here
        }
    }



    /**
     * Handle insertUpdate events (required by DocumentListener)
     *
     * @param e   The event
     */
    public void insertUpdate(DocumentEvent e)
    {
        Document    source;

        source = e.getDocument();

        try 
        {
            System.out.println("In insertUpdate:\n"+
                         source.getText(0,source.getLength())+
                         "\n\n");
        } 
        catch (BadLocationException ble) 
        {
            // Shouldn't get here
        }
    }




    /**
     * Handle removeUpdate events (required by DocumentListener)
     *
     * @param e   The event
     */
    public void removeUpdate(DocumentEvent e)
    {
        Document    source;

        source = e.getDocument();

        try 
        {
            System.out.println("In removeUpdate:\n"+
                         source.getText(0,source.getLength())+
                         "\n\n");
        } 
        catch (BadLocationException ble) 
        {
            // Shouldn't get here
        }
    }


}
        
Using a Text Component (cont.)

An Example Subject

javaexamples/usinggui/TextFieldDriver.java
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;

/**
 * An example that uses a text field
 *
 * @version 1.0
 * @author  Prof. David Bernstein, James Madison Univeristy
 */
public class TextFieldDriver
{

    /**
     * The entry point of the example
     *
     * @param args   The command line arguments
     */
    public static void main(String[] args)
    {
        Container     contentPane;
        JFrame   frame;
        JTextArea     textArea;
        JLabel        titleLabel;

        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       

        contentPane = frame.getContentPane();
        contentPane.setLayout(new BorderLayout());

        titleLabel = new JLabel();
        titleLabel.setText("A TextField Example");
        contentPane.add(titleLabel, BorderLayout.NORTH);

        textArea = new JTextArea();

        contentPane.add(textArea, BorderLayout.SOUTH);

        // Setup the observer
        TextFieldHandler handler = new TextFieldHandler();
        Document model = textArea.getDocument();
        model.addDocumentListener(handler);

        
        frame.setSize(400,200);
        frame.setVisible(true);
    }
}
        
Using a JList javax.swing.JList
Using a JList javax.swing.JList (cont.)

An Example Observer

javaexamples/usinggui/ListHandler.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;

/**
 * An example that illustrates the use of lists.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class ListHandler implements ListSelectionListener
{
    /**
     * Default constructor.
     */
    public ListHandler()
    {
    }

    /**
     * Handle valueChanged events 
     * (required by ListSelectionListener)
     *
     * @param e   The event
     */
    public void valueChanged(ListSelectionEvent e)
    {
        int       i;
        JList     list;
        Object[]  selected;


        list = (JList)(e.getSource());
        selected = list.getSelectedValues();

        for (i=0; i < selected.length; i++) 
        {
            System.out.println((String)(selected[i]) + 
                               "\t"+e.getValueIsAdjusting());
        }
    }
}
        
Using a JList javax.swing.JList (cont.)

An Example Subject

javaexamples/usinggui/ListDriver.java
import java.awt.*;
import javax.swing.*;

/**
 * An example that uses a text field
 *
 * @version 1.0
 * @author  CS349, James Madison Univeristy
 */
public class ListDriver
{

    /**
     * The entry point of the example
     *
     * @param args   The command line arguments
     */
    public static void main(String[] args)
    {
        Container     contentPane;
        JFrame        frame;
        JList         list;
        JLabel        titleLabel;
        String[]      data;        
        
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       

        contentPane = frame.getContentPane();
        contentPane.setLayout(new BorderLayout());

        titleLabel = new JLabel();
        titleLabel.setText("A List Example");
        contentPane.add(titleLabel, BorderLayout.NORTH);

        data = new String[5];
        data[0] = "CS149";
        data[1] = "CS159";
        data[2] = "CS240";
        data[3] = "CS261";
        data[4] = "CS345";

        list = new JList(data);
        list.setSelectionMode(
              ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        

        contentPane.add(list, BorderLayout.WEST);


        // Setup the observer
        ListHandler handler = new ListHandler();
        list.addListSelectionListener(handler);
        
        
        frame.setSize(400,200);
        frame.setVisible(true);
    }
}
        
Using a JComboBox javax.swing.JComboBox
Using a JComboBox javax.swing.JComboBox (cont.)

An Example Observer

javaexamples/usinggui/ComboBoxHandler.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

/**
 * A frame that illustrates the use of combo boxes.
 * Note that this frame listens to events itself.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class ComboBoxHandler implements ItemListener
{
    /**
     * Default constructor
     */
    public ComboBoxHandler()
    {
    }

    /**
     * Handle itemStateChanged events (required by ItemListener)
     *
     * @param e   The event
     */
    public void itemStateChanged(ItemEvent e)
    {
        int       state;
        String    selected;

        selected = (String)(e.getItem());
        state = e.getStateChange();

        if (state == ItemEvent.SELECTED) 
        {
            System.out.println("Selected: "+selected);
        }
    }
}
        
Using a JComboBox javax.swing.JComboBox (cont.)

An Example Subject

javaexamples/usinggui/ComboBoxDriver.java
import java.awt.*;
import javax.swing.*;

/**
 * An example that uses a combobox.
 *
 * @version 1.0
 * @author  Prof. David Bernstein, James Madison Univeristy
 */
public class ComboBoxDriver
{

    /**
     * The entry point of the example
     *
     * @param args   The command line arguments
     */
    public static void main(String[] args)
    {
        Container     contentPane;
        JFrame        frame;
        JComboBox     comboBox;
        JLabel        titleLabel;

        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       

        contentPane = frame.getContentPane();
        contentPane.setLayout(new BorderLayout());

        titleLabel = new JLabel();
        titleLabel.setText("A ComboBox Example");
        contentPane.add(titleLabel, BorderLayout.NORTH);

        String[] data = new String[5];
        data[0] = "CS149";
        data[1] = "CS159";
        data[2] = "CS240";
        data[3] = "CS261";
        data[4] = "CS345";

        comboBox = new JComboBox(data);
        comboBox.setEditable(true);
        contentPane.add(comboBox, BorderLayout.SOUTH);

        // Setup the observer
        ComboBoxHandler handler = new ComboBoxHandler();
        comboBox.addItemListener(handler);

        
        frame.setSize(400,200);
        frame.setVisible(true);
    }
}
        
Responding to JSlider Objects
Responding to JSlider Objects (cont.)
An Example Observer
javaexamples/usinggui/SliderHandler.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

/**
 * An example that uses a slider
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class SliderHandler implements ChangeListener
{
    private JLabel displayArea;
    
    /**
     * Explicit Value Constructor
     */
    public SliderHandler(JLabel displayArea)
    {
        this.displayArea = displayArea;        
    }


    /**
     * Handle stateChanged message (required by ChangeListener)
     *
     * @param event   The ActionEvent that generatedt his message
     */
    public void stateChanged(ChangeEvent event)
    {
       int           value;       
       JSlider       source;
       
       source = (JSlider)event.getSource();
       value = source.getValue();
       displayArea.setText("I'm now at: "+value);
    }
    
}
        
Responding to JSlider Objects (cont.)
An Example Subject
javaexamples/usinggui/SliderDriver.java
import java.awt.*;
import javax.swing.*;


/**
 * An example that uses a slider
 *
 * @author  Prof. David Bernstein, James Madison Univeristy
 * @version 1.0
 */
public class SliderDriver
{

    /**
     * The entry point of the example
     *
     * @param args   The command line arguments
     */
    public static void main(String[] args)
    {
        Container   contentPane;
        JFrame      frame;
        JSlider     slider;
        JLabel      titleLabel;

        frame = new JFrame("A Really Amazing Window!");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Get the content pane
        contentPane = frame.getContentPane();
        contentPane.setLayout(null);

        // Construct the widgets/components
        titleLabel   = new JLabel("A Slider Example");
        slider       = new JSlider(0, 100, 50);

        // Layout the content pane
        contentPane.add(titleLabel);
        titleLabel.setBounds(60,20,290,30);

        contentPane.add(slider);
        slider.setBounds(60,100,290,30);

        // Setup the observer
        SliderHandler handler = new SliderHandler(titleLabel);
        slider.addChangeListener(handler);
        
        frame.setSize(400,400);
        frame.setVisible(true);
    }
}
        
Menus