Search code examples
javajcomboboxawtrobot

How can I avoid using this robot to trigger my JComboBox?


I am using a JComboBox to load a table per the selected item. The combo box is editable and I am using the autoCompleteDecorator on it. The problem I was having is all of my code would fire while searching the combo box instead of waiting for the VK_ENTER. So, I had to use a variable to store the string "enter" when the enter key is struck. Everything is working ok (bodged together but working) except for me having to strike the enter key twice to perform commit the selected item.. So instead of the end user having to strike the key twice, I added a robot.

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();
            }
        }
    }
});

So there is my KeyListener, here is my 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….
        }
    }
}

Is there a way for me to eliminate the need for the KeyListener all together? I suppose what I want to accomplish is only commit the search on the Enter key press or Left mouse click.


Solution

  • Instead of using a KeyListener to monitor the change to the editor, attach an ActionListener to the editor or combobox which will perform the same action in a platform independent manner