Input with a Button

Context

You're writing a program with a graphical user interface. You want the user to click a button to change the state of the program or cause some action to occur.

Example

When the button is pushed, the word "Ouch!" is added to the text area.
This example is demonstrated by the following applet, although the code below would be suitable for use as a special panel in an application's GUI.
Note: The application would need to declare a JFrame and main method elsewhere. See Graphical Application for an example using JFrame

{short description of image}
Applet Image of the JPanel
package Patterns.Button;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.Color;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class ButtonEx extends JPanel
{  // Instantiate a button and a textarea.
   private JButton pushMe = new JButton();
   private JTextArea ta = new JTextArea("", 5, 15, TextArea.SCROLLBARS_VERTICAL_ONLY);

   public ButtonEx()
   {  // Set the attributes for the buttons
      pushMe.setBackground(Color.red);
      pushMe.setLabel("Push Me");
      pushMe.addActionListener(new ButtonListener());

      // Add all the widgets to the applet
      this.getContentPane().add(pushMe);
      this.getContentPane().add(ta);
   }

   // The listener for the button.
   private class ButtonListener implements ActionListener
   {  public void actionPerformed(ActionEvent evt)
      {  if (ta.getText().length() > 0)
         {  ta.append("\n");  }
         ta.append("Ouch!");
      }
   }
}

Pattern

package <name-of-package>;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class <name-of-class> extends JPanel
{  private JButton <name-of-button> = new JButton("<label>");

   public <name-of-class>()
   {  <name-of-button>.addActionListener(
             new <name-of-actionlistenerclass>());
      this.getContentPane().add(<name-of-button>);
   }
   
   private class <name-of-actionlistenerclass> implements ActionListener
   {  public void actionPerformed(ActionEvent evt)
      {  <code-to-do-when-button-is-clicked>
      }
   }
}

Notes

Related Patterns