Use an Action object to create a JButton - Java Swing

Java examples for Swing:JButton

Introduction

An Action represents the state and the behavior of a button.

An Action can have the text, icon, mnemonic, tool tip text, other properties, and the ActionListener.

Action is an interface.

The AbstractAction class provides the default implementation for the Action interface.

Demo Code

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Main extends JFrame {

  JButton closeButton1;//www  .ja va 2  s. c  o  m
  JButton closeButton2;
  Action closeAction = new CloseAction();

  public class CloseAction extends AbstractAction {
    public CloseAction() {
      super("Close");
    }

    @Override
    public void actionPerformed(ActionEvent event) {
      System.exit(0);
    }
  }
  public Main() {
    super("Action object with JButton");

    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setLayout(new FlowLayout());
    Container contentPane = this.getContentPane();

    closeButton1 = new JButton(closeAction);
    closeButton2 = new JButton(closeAction);

    contentPane.add(closeButton1);
    contentPane.add(closeButton2);
  }

  public static void main(String[] args) {
    Main frame = new Main();
    frame.pack();
    frame.setVisible(true);
  }
}

Related Tutorials