【发布时间】:2016-07-28 12:02:07
【问题描述】:
我正在尝试向我的 JButton 添加快捷方式。我已经阅读了How to Use Key Bindings 教程,并且我还阅读了此页面 How to use Key Bindings instead of Key Listeners 以及关于键绑定的其他问题,但还没有找到任何答案
我的尝试:
public class Example extends JFrame {
public static void main(String args[]) {
Example example = new Example();
}
Example(){
Action action = new Action() {
@Override
public Object getValue(String key) {
return null;
}
@Override
public void putValue(String key, Object value) {
}
@Override
public void setEnabled(boolean b) {
}
@Override
public boolean isEnabled() {
return false;
}
@Override
public void addPropertyChangeListener(PropertyChangeListener listener) {
}
@Override
public void removePropertyChangeListener(PropertyChangeListener listener) {
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Hello World!");
}
};
JButton button = new JButton("Hello World!");
button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("RIGHT"), "doSomething");
button.getActionMap().put("doSomething", action);
button.addActionListener(action);
add(button);
setVisible(true);
pack();
}
}
我也尝试过这样:getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true), "doSmth");
但似乎没有任何效果,我做错了什么?
【问题讨论】:
-
你的第一个例子对我有用。 “并且具有
actionPerformed功能”是什么意思? -
发布minimal reproducible example。您的问题不在您提供的代码 sn-ps 中。
-
我已经编辑了问题,现在它显示
NextCardListener。我的意思是它应该这样做,对不起 -
提示:添加@user1803551(或重要的
@)以通知此人有新评论。在讨论这个主题时,请发布 MCVE(在此之前由于缺少一个而关闭)。 -
@EthanGills Pro 提示:
isEnabled()方法不适合大便和咯咯笑。你想在那里返回true,而不是false。一个更简单的方法是使用AbstractAction而不是Action,因为您显然不知道它们是如何工作的。另外,请不要在示例代码中发誓。
标签: java swing keyboard-shortcuts key-bindings