Java JButton create button from Action object with mnemonic key and short description(tooltip)

Description

Java JButton create button from Action object with mnemonic key and short description(tooltip)

import java.awt.FlowLayout;
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.JFrame;

public class Main extends JFrame {
  public Main() {
    super("Action object with JButton");

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

    JButton closeButton1;/*from w  w  w.j av  a  2 s  . c  o 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");
    putValue(Action.MNEMONIC_KEY, KeyEvent.VK_C);
    putValue(Action.SHORT_DESCRIPTION, "Closes the application");
  }

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



PreviousNext

Related