【发布时间】:2018-03-17 10:58:26
【问题描述】:
我在 java 中添加了一些键盘快捷键,并且大部分时间它们都按预期工作。 仅当焦点在组合框内,并且组合框包含以快捷方式开头的值时,然后按该键更改组合框值,而不运行操作。
在以下示例中,我希望按下 1/2 将始终调用 button1/button2,但它正在更改组合中的值。
有什么简单的方法可以改变这种行为吗?
+注意,我尝试在函数 registerKeyboardAction 中设置 3 参数 而是:
JComponent.WHEN_IN_FOCUSED_WINDOW
到:
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
这没有帮助。
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class TestCombo {
public static void main(String[] args) {
JFrame frame = new JFrame("TEST");
JPanel panel = new JPanel();
JComboBox<String> comboBox = new JComboBox<String>(new String[]{"1", "2", "3", "4", "5"});
panel.add(comboBox);
JButton button1 = new JButton(new TextAction("Text1"));
JButton button2 = new JButton(new TextAction("Text2"));
panel.add(button1);
panel.add(button2);
panel.registerKeyboardAction(button1.getAction(), KeyStroke.getKeyStroke(KeyEvent.VK_1, 0, false), JComponent.WHEN_IN_FOCUSED_WINDOW);
panel.registerKeyboardAction(button2.getAction(), KeyStroke.getKeyStroke(KeyEvent.VK_2, 0, false), JComponent.WHEN_IN_FOCUSED_WINDOW);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(400, 200));
frame.pack();
frame.setVisible(true);
}
private static class TextAction extends AbstractAction{
private String text;
public TextAction(String vText){
text = vText;
putValue(Action.NAME, text);
}
@Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, text);
}
}
}
【问题讨论】: