Jump to content

Events and Buttons

50% developed
From Wikibooks, open books for an open world


On the last page, we created an application that passively displays a "Hello, world" message. However, that gets boring quickly. In this chapter, we'll talk about swing events and look at the JButton class, and we'll build a small application that includes a JButton with a JLabel, and use it to introduce the concept of Layouts.

Events

[edit | edit source]

Events are a fundamental part of how swing works. Various actions on the part of the user cause components to fire various types of events. Other Java objects can register as listeners of events with any components whose events they are interested in. In order to be a listener, the object must implement the appropriate listener interface (ie, ActionListener for action events, FocusListener for focus events, etc.), which contains methods which are called when the event is fired.

In Java, events themselves are objects, and instances of event classes. The event classes are located in the packages java.awt.event and javax.swing.event. A few common classes of events are:

  • ActionEvent — a (somewhat generic) event fired by some objects, including JButtons
  • MouseEvent — fired when the user does something with the mouse, such as a click, drag, or more general motion
  • KeyEvent — fired when the user presses, releases, or more generally types a key on the keyboard

In order to see how events are used, we'll look at JButtons so that we can build an example.

JButtons

[edit | edit source]

A JButton is a component that, like a JLabel, can hold text, images, or both. However, as we'd expect, it also has the property that the user can "push" it by clicking on it, which causes it to fire an event (specifically, an action event). In this example, we'll more or less redo our previous example, except that we'll add a JButton. In the next section, we'll add functionality so that pressing the button does something.

Here's the code that creates the previous "Hello, world" application, plus a button at the bottom of the screen:

The window created by the code at left
Computer code A Swing application with buttons
import javax.swing.*;
import java.awt.BorderLayout; // The BorderLayout class
                  // lives in java.awt.  We
                  // use its constants to tell
                  // the JFrame where we want the
                  // components to go.

// expanded version of the hello application,
// but with a button below.
public class HelloWithButton {

    public static void main(String[] args) {
        
        // construct the JLabel,
        // an overloaded version of the constructor
        // allows us to specify the alignment off the
        // bat
        JLabel label = new JLabel
            ("Hello, World!", SwingConstants.CENTER);
        
        // create the button. The text in the
        // constructor will be visible on the
        // button.
        JButton button = new JButton("Button");
        
        // create the frame
        JFrame frame = new JFrame("Hello");
        
        // add the label and the button to the
        // frame, using layout constants.
        frame.add(label, BorderLayout.CENTER);
        frame.add(button, BorderLayout.SOUTH);
        
        frame.setSize(300, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
        frame.toFront();
    }
}

What you should see is a frame appear that contains the text "Hello, World!" in the center, along with a button labeled "Button" at the bottom. You can click on the button, but it doesn't do anything.

In this example, we not only added the components to the frame, but specified where they should go. Every component which contains other components has a LayoutManager object, which controls how the components are laid out, and different layout managers lay out their components differently. A few examples of layout managers are GridLayout, CardLayout, and BorderLayout. This last is the default layout manager of a JFrame (although we can change the layout manager of a component by using its setLayout() method). Although layout managers are covered in more detail in a later chapter, we'll say here that BorderLayout managers divide their space into five regions, and each is associated with a constant in the BorderLayout class. The constants (which explain the regions) are:

  • BorderLayout.NORTH,
  • BorderLayout.SOUTH,
  • BorderLayout.EAST,
  • BorderLayout.WEST and
  • BorderLayout.CENTER.

If you're adding a component to a container that is using a BorderLayout, you can pass one of these constants as an optional second parameter to the add() method to specify where the component should be placed. If no constant is specified, the layout manager by default places the new component in the center. I would encourage you to experiment with the previous example and change the layout parameters, and observe the effect.


Clipboard

To do:
Add screenshots.


Clipboard

To do:
Use separated examples.