JButton ActionListener Example


JButton ActionListener Example Note: It is advised to read Java JFC Swing Introduction and Swing Overview before reading this.

Just like AWT button, the Swing JButton also can be given event-handling. The same program of AWT button (of 8 steps) is converted into JButton.

In the following program, as per the JButton clicked, the background of the frame changes. It is advised to read Java AWT Button – Learning GUI – 8 Steps for basic steps involved in creating GUI.

JButton ActionListener Example

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

public class JButtonInAction extends JFrame implements ActionListener
{
  JButton rb, gb, bb ;
  Container c;
  public JButtonInAction( )
  {
    c = getContentPane();		      // create the container
    c.setLayout(new FlowLayout());	      // set the layout

    rb = new JButton("Red");
    gb = new JButton("Green");
    bb = new JButton("Blue");

    rb.addActionListener(this);		      // linking to listener
    gb.addActionListener(this);
    bb.addActionListener(this);

    c.add(rb);    c.add(gb);    c.add(bb);    // adding buttons
                   
    setTitle("Buttons In Action");            // usual set methods of AWT frame
    setSize(300, 350);
    setVisible(true);
  }				               // override the abstract method of ActionListener
  public void actionPerformed(ActionEvent e)
  {
     String str = e.getActionCommand();        // know which button user clicked
     if(str.equals("Red"))                     // here, Red is the label of the Button rb
          c.setBackground(Color.red);	       // here, red is the color
     else if(str.equals("Green"))                            
          c.setBackground(Color.green);
     else if(str.equals("Blue"))                            
          c.setBackground(Color.blue);
  }
  public static void main(String args[])
  {
    new JButtonInAction();  
  }
}


JButton ActionListener Example
Output Screenshot on JButton ActionListener Example

c = getContentPane();
c.setLayout(new FlowLayout());

Read Swing Overview to learn on lightweight and heavyweight components, content pane and Container.

Leave a Comment

Your email address will not be published.