next up previous contents
Next: Three buttons Up: Some examples of event Previous: Some examples of event   Contents

A button

A button is a graphical object that can be clicked. There is only one thing that a user can do with a button--click it. Thus, when a button is clicked, an appropriate listener has to be informed that it was clicked, along with the identity of the button. The built-in button class in Swing is called JButton. The interface ActionListener describes classes that can listen to button clicks. When a button is clicked, the method actionPerformed(...) is invoked in each ActionListener that is associated with this button.

Thus, to construct a button in Java, we need to declare a JButton and provide a class that listens to it. At the minimum we need the following.

   class MyButtons{
     private JButton b;

     public MyButtons(ActionListener a){
        b = new JButton("MyButton");  // Set the label on the button
        b.addActionListener(a);       // Associate an listener
     }
   }

   class MyListener implements ActionListenerP
    public void actionPerformed(ActionEvent evt){
        ...                           // What to do when a button 
        ...                           // is pressed
    }

   class XYZ{
     MyListener l = new MyListener(); // Create an ActionListener l
     MyButtons m = new MyButtons(l);  // Create a button m, listened to by l

Unfortunately, we have to do a lot more to actually display a button. First, we have to generate a ``container'' to hold the button. Usually, this is done using an object called a panel--the corresponding class in Swing is JPanel. Here is how to define a panel that contains a single button. The enclosing panel listens to the button click. The import statements at the top include the appropriate packages from AWT and Swing.

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

public class ButtonPanel extends JPanel implements ActionListener{

    private JButton redButton;

    public ButtonPanel(){
        redButton = new JButton("Red");     // Create the button
        redButton.addActionListener(this);  // Make the panel listen
                                            //   to the button
        add(redButton);                     // Embed the button in the
                                            //   panel
    }
        
    public void actionPerformed(ActionEvent evt){
        Color color = Color.red;            // Set the background colour
        setBackground(color);               //   to red when the button
        repaint();                          //   is clicked
    }

}

In Java, a panel cannot be displayed directly. We have to embed the panel into a frame--in Swing, the class we need is JFrame. A JFrame can generate seven different types of events that are handled by objects that implement WindowListener. These events correspond to actions such as iconizing a window, making a window occupy the full screen, killing the window, .... Each of these actions invokes a different function in WindowListener. It is important to note that this classification of the seven different types of actions is done automatically by Swing--we do not need to write an elaborate case-analysis in a WindowListener to decipher the nature of the event.

Here is a simple frame that includes a ButtonPanel. The class ButtonFrame acts as its own WindowListener. For six of the seven functions, we have provided just a stub. The only window event that ButtonFrame handles is the one that kills the window. If the window is killed, the corresponding Java program exits. If we do not write something appropriate for the method windowClosing(WindowEvent e), when the user kills the window the window manager will delete the frame but the underlying Java program will continue to run ``invisibly''!

The only other complication in this example is the use of ContentPane. A JFrame is a ``complex'' object, made up of different conceptual ``layers''. One of these layers is called the ContentPane. When we add objects to the JFrame, we actually add them to the ContentPane. Thus, to add a ButtonPanel to a ButtonFrame, we first get access to the ContentPane of the ButtonFrame and add the ButtonPanel to the ContentPane.

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

public class ButtonFrame extends JFrame  implements WindowListener {
    Private Container contentPane;

    public ButtonFrame(){
        setTitle("ButtonTest");
        setSize(300, 200);
        addWindowListener(this);              // ButtonFrame is its
                                              //   own listener
        contentPane = this.getContentPane();  // ButtonPanel is added
        contentPane.add(new ButtonPanel());   //   to the contentPane
    }

    // Seven methods required for implementing WindowListener
    // Six out of seven are dummies (stubs)

    public void windowClosing(WindowEvent e){  // Exit when window 
        System.exit(0);                        //    is killed
    }

    public void windowActivated(WindowEvent e){}

    public void windowClosed(WindowEvent e){}

    public void windowDeactivated(WindowEvent e){}

    public void windowDeiconified(WindowEvent e){}

    public void windowIconified(WindowEvent e){}

    public void windowOpened(WindowEvent e){}

}

Finally, here is a main method that creates and displays a ButtonFrame.

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

public class ButtonTest

{  public static void main(String[] args)
   {  JFrame frame = new ButtonFrame();
      frame.show();  
   }
}


next up previous contents
Next: Three buttons Up: Some examples of event Previous: Some examples of event   Contents
Madhavan Mukund 2004-04-29