Java Swing How to - Link Action to JDialog








Question

We would like to know how to link Action to JDialog.

Answer

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/*from  w w  w  . j a v a  2s . c  om*/
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.KeyStroke;

public class Main extends JFrame {
  static String exitName = "Exit";

  ExitAction exitAction = new ExitAction(exitName);

  public Main() {
    int MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();

    KeyStroke exitKey = KeyStroke.getKeyStroke(KeyEvent.VK_W, MASK);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);

    JMenu fileMenu = new JMenu("File");
    JMenuItem fileExit = new JMenuItem(exitAction);
    fileMenu.add(fileExit);
    JMenuBar menu = new JMenuBar();
    menu.add(fileMenu);

    JDialog d = new JDialog(this, "Dialog");
    JPanel p = new JPanel();
    p.getInputMap().put(exitKey, exitName);
    p.getActionMap().put(exitName, exitAction);
    p.add(new JButton(exitAction));
    d.add(p);
    d.pack();
    d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

    this.setJMenuBar(menu);
    this.pack();
    this.setSize(new Dimension(320, 240));
    this.setVisible(true);
    d.setLocation(this.getRootPane().getContentPane().getLocationOnScreen());
    d.setVisible(true);
  }

  public static void main(String[] args) {
    new Main();
  }
}

class ExitAction extends AbstractAction {
  int MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();

  KeyStroke exitKey = KeyStroke.getKeyStroke(KeyEvent.VK_W, MASK);

  public ExitAction(String name) {
    super(name);
    this.putValue(Action.MNEMONIC_KEY, exitKey.getKeyCode());
    this.putValue(Action.ACCELERATOR_KEY, exitKey);
  }

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