Java AbstractAction create action for JButton

Description

Java AbstractAction create action for JButton

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 {
  public Main() {
    super("Action object with JButton");

    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(new FlowLayout());

    JButton closeButton1;/*  ww  w.  ja  v a 2s.co m*/
    Action closeAction = new CloseAction();

    closeButton1 = new JButton(closeAction);

    getContentPane().add(closeButton1);
  }

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

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

  @Override
  public void actionPerformed(ActionEvent event) {
    System.exit(0);
  }
}



PreviousNext

Related