Java Swing KeyStroke get key stroke for shift and space

Description

Java Swing KeyStroke get key stroke for shift and 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");
      PrevFocusAction prevFocusAction = new PrevFocusAction();
      component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("shift F2"),
          prevFocusAction.getValue(Action.NAME));
      /*from w w  w.  j  a  v  a2 s. co  m*/
      component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("shift SPACE"),
          prevFocusAction.getValue(Action.NAME));
      
      component.getActionMap().put(prevFocusAction.getValue(Action.NAME), prevFocusAction);
   
      f.getContentPane().setLayout(new FlowLayout());
      f.add(new JTextField(10));
      f.add(component);
      f.add(new JTextField(10));

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

class PrevFocusAction extends AbstractAction {
   PrevFocusAction() {
     super("Move Focus Backwards");
   }

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



PreviousNext

Related