Java Swing How to - Register Key board Action with VK_SPACE for JDialog








Question

We would like to know how to register Key board Action with VK_SPACE for JDialog.

Answer

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
//from   w w w .j a v a 2 s.c  om
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.ListSelectionModel;

public class Main {
  public static void main(String[] args) {
    JDialog dialog;
    JList jlist;
    ActionListener otherListener = new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        System.out.println("current");
      }
    };
    JButton okButton = new JButton("OK");
    okButton.addActionListener(e -> close(true));
    JButton cancelButton = new JButton("Cancel");
    cancelButton.addActionListener(e -> close(false));
    jlist = new JList(new String[] { "A", "B", "C", "D", "E", "F", "G" });
    jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    jlist.setVisibleRowCount(5);
    JScrollPane scroll = new JScrollPane(jlist);
    JPanel buttonsPanel = new JPanel(new FlowLayout());
    buttonsPanel.add(okButton);
    buttonsPanel.add(cancelButton);
    JPanel content = new JPanel(new BorderLayout());
    content.add(scroll, BorderLayout.CENTER);
    content.add(buttonsPanel, BorderLayout.SOUTH);
    dialog = new JDialog((Frame) null, true);
    dialog.setContentPane(content);
    dialog.pack();
    dialog.getRootPane().registerKeyboardAction(otherListener,
        KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
        JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

    dialog.getRootPane().registerKeyboardAction(otherListener,
        KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
        JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

    dialog.getRootPane().getInputMap()
        .put(KeyStroke.getKeyStroke("SPACE"), "doSomething");
    dialog.getRootPane().getActionMap()
        .put("doSomething", new AbstractAction() {
          @Override
          public void actionPerformed(ActionEvent e) {
            System.exit(0);
          }
        });
    dialog.setVisible(true);
  }

  static void close(boolean commit) {
    if (commit) {
      System.out.println("Now saving...");
    } else {
      System.out.println("Now closing...");
      System.exit(0);
    }
  }
}