Java Swing How to - Create JButton from Action object








Question

We would like to know how to create JButton from Action object.

Answer

/*from   ww w. j a v  a  2s .c o  m*/
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

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

class ShowAction extends AbstractAction {
  public ShowAction() {
    super("About");
    putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_A));
  }

  public void actionPerformed(ActionEvent actionEvent) {
        System.out.println("java2s.com");
  }
}

public class Main {
  public static void main(final String args[]) {
    JButton bn = new JButton(new ShowAction());

    JOptionPane.showMessageDialog(null, bn);
  }
}