CIS 160 - GUI Notes II

Objectives

  • Create and use event handlers
  • Shut down the GUI thread in a program when exiting

Commonly needed imports for GUIs

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

Event handlers

  • Event handlers are objects
  • We create an event handler using the new keyword, just like other objects
  • Event handlers are called listeners and must "implement" the predefined listener for the type of event they are meant to handle
  • The event handler, or listener, is then added to the component it will be handling events for
  • Example of adding an event handler to an "Exit" button: JButton btnExit = new JButton("Exit"); // we will assume the JButton is added to a GUI container somewhere else MyExitListener exitListener = new MyExitListener(); btnExit.addActionListener(exitListener);
  • Example of event handler definition: class MyExitListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); // shuts down all application threads } }
  • You usually want to handle the close window event as well. JFrame objects have a shortcut for handling that. The following code ends the application when the window is closed: setDefaultCloseOperation(EXIT_ON_CLOSE)

Example

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class GUIDemo1 extends JFrame { public static void main(String[] args) { GUIDemo1 app = new GUIDemo1(); } public GUIDemo1() { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } private void createAndShowGUI() { Container c = getContentPane(); c.setLayout(new BorderLayout()); JButton btnExit = new JButton("Exit"); ExitListener listener = new ExitListener(); btnExit.addActionListener(listener); c.add(btnExit, BorderLayout.SOUTH); setSize(200, 300); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } } class ExitListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } }

Resource