Java Swing KeyStroke create for control alt 7

Description

Java Swing KeyStroke create for control alt 7

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.KeyStroke;

public class Main {
   public static void main(String[] a) {
      //from w  w  w.ja v a  2  s  . c o  m
      JFrame frame = new JFrame("KeyStroke Sample");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JButton buttonA = new JButton("Press 'control alt 7'");
      Action actionListener = new AbstractAction() {
         public void actionPerformed(ActionEvent actionEvent) {
            JButton source = (JButton) actionEvent.getSource();
            System.out.println(source.getText());
         }
      };
      
      String ACTION_KEY = "theAction";
      
      KeyStroke controlAlt7 = KeyStroke.getKeyStroke("control alt 7");
      InputMap inputMap = buttonA.getInputMap();
      inputMap.put(controlAlt7, ACTION_KEY);
      ActionMap actionMap = buttonA.getActionMap();
      actionMap.put(ACTION_KEY, actionListener);
      frame.add(buttonA);
      frame.setSize(400, 200);
      frame.setVisible(true);
   }
}



PreviousNext

Related