【问题标题】:How can I avoid using this robot to trigger my JComboBox?我怎样才能避免使用这个机器人来触发我的 JComboBox?
【发布时间】: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 附加到它,这将以更独立于平台的方式完成相同的工作

标签: java jcombobox awtrobot


【解决方案1】:

不要使用KeyListener 来监视对编辑器的更改,而是将ActionListener 附加到编辑器或组合框,它将以独立于平台的方式执行相同的操作

【讨论】:

  • 谢谢@MadProgrammer 我明天回到办公室时会试一试。
猜你喜欢
  • 2010-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多