Java Swing KeyStroke get key stroke for space

Description

Java Swing KeyStroke get key stroke for space


import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.KeyStroke;

public class Main {
   public static void main(String[] args) {
      JFrame f = new JFrame();

      JButton component = new JButton("OK");
      NextFocusAction nextFocusAction = new NextFocusAction();

      component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("SPACE"),
            nextFocusAction.getValue(Action.NAME));

      component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("F2"),
            nextFocusAction.getValue(Action.NAME));

      component.getActionMap().put(nextFocusAction.getValue(Action.NAME), nextFocusAction);

      f.getContentPane().setLayout(new FlowLayout());
      f.add(new JTextField(10));
      f.add(component);/* w w  w  .  j av  a  2 s.  c  om*/
      f.add(new JTextField(10));

      f.setSize(310, 200);
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.setVisible(true);
   }
}

class NextFocusAction extends AbstractAction {
   public NextFocusAction() {
      super("Move Focus Forwards");
   }

   public void actionPerformed(ActionEvent evt) {
      ((Component) evt.getSource()).transferFocus();
   }
}



PreviousNext

Related