【发布时间】:2015-01-02 15:32:06
【问题描述】:
我正在使用 JComboBox 为每个选定项目加载一个表格。 组合框是可编辑的,我在它上面使用了 autoCompleteDecorator。 我遇到的问题是我的所有代码都会在搜索 组合框而不是等待 VK_ENTER。所以,我不得不使用一个变量 当敲击回车键时存储字符串“enter”。一切正常 好的(在一起但工作)除了我必须敲击输入 键两次以执行提交选定的项目。所以而不是最终用户 不得不敲两次键,我添加了一个机器人。
static JComboBox<String> drivers = new JComboBox<String>();
drivers.setEditable(true);
AutoCompleteDecorator.decorate(drivers);
drivers.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent kEvent) {
if (kEvent.getKeyChar() == KeyEvent.VK_ENTER) {
lastKey="enter";
try{
Robot myBot = new Robot();
myBot.keyPress(KeyEvent.VK_ENTER);
}catch (AWTException e){
JOptionPane.showMessageDialog(frame, "Something has gone terribly wrong.","myBot Failure",JOptionPane.WARNING_MESSAGE);
e.printStackTrace();
}
}
}
});
所以有我的 KeyListener,这是我的 ActionListener:
drivers.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent eAction){
if(lastKey=="enter" || !((eAction.getModifiers() & InputEvent.BUTTON1_MASK) == 0)){
lastKey="";
//Query the DB, load the table accordingly
//And do a bunch of other stuff….
}
}
}
有没有办法让我一起消除对 KeyListener 的需求? 我想我想要完成的只是在 Enter 键上提交搜索 按或鼠标左键单击。
【问题讨论】:
-
您应该检查如何正确比较字符串,并且您应该考虑将常量
KeyEvent.VK_ENTER保存为lastKey而不是字符串(以防无法避免您的机器人)。跨度> -
谢谢,@Tom,将 lastKey== 更改为 lastKey.equals().. 据我所知,在 ListComponent 的 KeyPress 事件中,它只是将 SelectedItem 放入 EditorComponent,第二个 Enter(由机器人执行)触发 ActionEvent?对不起,我的无知。
-
不要使用 KeyListener 来监视编辑器的更改,而是将 ActionListener 附加到它,这将以更独立于平台的方式完成相同的工作