[英]Java Swing get input
How can I change this code to accept any key (not only F5) and print the key? 如何更改此代码以接受任何密钥(不仅限于F5)并打印密钥?
component.getRootPane().getInputMap(JRootPane.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), "F5 Pressed");
component.getRootPane().getActionMap().put("F5 Pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
// Code here
}
});
how can I ("cahnhe") this code to accept any key (not only F5) and print the key?
我如何(“ cahnhe”)此代码接受任何密钥(不仅是F5)并打印密钥?
sorry this question doesn't make me some sence, in this form 抱歉,这个问题并没有让我有这种感觉
basic is described in tutorial , 基本内容在教程中有所介绍 ,
component.getRootPane()
could be valid only for JFrame
, JDialog
, JWindow
, practically only JFrame
has accesible RootPane
component.getRootPane()
仅对JFrame
, JDialog
, JWindow
,实际上只有JFrame
具有可访问的RootPane
otherwise to add Input/ActionMap
to the desired JComponent
directly 否则直接将
Input/ActionMap
添加到所需的JComponent
Use KeyboardFocusManager
to register a KeyEventDispatcher
: 使用
KeyboardFocusManager
注册KeyEventDispatcher
:
KeboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
@Override
public boolean dispatchKeyEvent(KeyEvent ke) {
if (yourComponent.hasFocus && ke.getID == KeyEvent.KEY_TYPED) {
// Your code here
// Use ke.getKeyChar() to detect which key was pressed.
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.