Java: JButton

Description

There are a few steps in using a button: declaring it, creating it, adding it to a container (the content pane or a JPanel), and adding a listener that has code to execute when the user clicks on the button. Images can be used on buttons, including automatic rollover effects.

Constructors

Assume these declarations.
   String text;
   Icon   image;
   
JButton btn = new JButton(text);
JButton btn = new JButton(text, image);
JButton btn = new JButton(image);

Common methods

Assume these declarations:
   JButton btn;
   ActionListener listener;
   boolean b;
   
   //--- Buttons always have action listeners.
   btn.addActionListener(listener);
   btn.setEnabled(b);
   

Events

When a button is clicked, the actionPerformed() method is called for all of the button's listeners. It is passed an ActionEvent, which is generally ignored, but can be used to identify which component generated the event if several share the same listener. The example below shows the creation of a button, attaching a listener, and adding the button to a container.

Example

Typically a button is assigned to a local variable (not an instance variable) and an anonymous action listener is added to it. The listener often calls another method to do everything because separating the code to build the user interface and do the "semantics" makes a program clearer and easier to modify.
JButton mybtn = new JButton("Do Something");
mybtn.addActionListener(
    new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            doMyAction();  // code to execute when button is pressed
        }
    }
);
. . .
content.add(mybtn);  // add the button to a JPanel (eg, content).