Event-Driven Programming in GUIs
An Introduction with Examples in Java (Swing) |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
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."); } } }
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); } }
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); } }
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"); } } } }
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); } }
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); } }
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 } } }
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); } }
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()); } } }
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); } }
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); } } }
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); } }
JSlider
ObjectsChangeEvent
ChangeListener
void stateChanged(ChangeEvent event)
JSlider
Objects (cont.)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); } }
JSlider
Objects (cont.)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); } }