I am Stuck in some Step that I Can't Add a Shorcut Key like: CTRL+SPACE to my program , I am Searching for one week and I could'd find any answers .
Asked
Active
Viewed 3,247 times
5
-
5Read about key bindings: http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html – Branislav Lazic Dec 20 '12 at 20:09
1 Answers
9
You'll want to look at the Java Tutorial for a good overview of Key Bindings.
Here's a quick example:
import java.awt.event.*;
import javax.swing.*;
public class KeyBindings extends Box{
public KeyBindings(){
super(BoxLayout.Y_AXIS);
final JTextPane textArea = new JTextPane();
textArea.insertComponent(new JLabel("Text"));
add(textArea);
Action action = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
textArea.setText("New Text");
}};
String keyStrokeAndKey = "control SPACE";
KeyStroke keyStroke = KeyStroke.getKeyStroke(keyStrokeAndKey);
textArea.getInputMap().put(keyStroke, keyStrokeAndKey);
textArea.getActionMap().put(keyStrokeAndKey, action);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new KeyBindings());
frame.pack();
frame.setVisible(true);
}
}

Nick Rippe
- 6,465
- 14
- 30
-
guess What ! It was Worked . Thanks For The Advice and thanks for the solution it's the same for JTextField and i will look up keyBindings . – Azad Dec 21 '12 at 18:54