I want to know how to add shortcuts similar to Emacs's in my Java application. For example C-x C-f and C-开发者_运维技巧x b.
Thanks.
Java provides a means to identify Modifier keys. By Modifier keys I mean
- Alt -- e.isAltDown();
- Ctrl -- e.isControlDown();
- Shift -- e.isShiftDown()
These acan be paired with other normal key press buttons from your keyboard to identify whether a combination has been pressed.
if( (e.isControlDown() && e.getKeyCode() == KeyEvent.VK_X) )
{
}
e.getModifiers() can be used to identify the modifier as well as the mouse button clicked. This returns bit mask.
See here.
http://www.leepoint.net/notes-java/GUI-lowlevel/keyboard/keyboard.html
I would use it something like this for Ctrl. This is overly simplified code, but you will get an idea.
JTextField sampleTxtFld= new JTextField();
sampleTxtFld.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e)
{
if((e.isControlDown() && e.getKeyCode() == KeyEvent.VK_X)
{
//identifies whether Ctrl + X has been pressed
// do some action here
}
}
public void keyReleased(KeyEvent e)
{
//some key released code here
}
public void keyTyped(KeyEvent e) {
}
});
As far as I know EMACS is an editor. If you want to change the KeyStrokes for editing command on Swing text components then you need to use Key Bindings. You can use the existing text Actions but just bind them to different KeyStrokes. See Key Bindings for a list of all the default bindings an some example of how to rebind and Action.
精彩评论