简体   繁体   中英

Java - ActionEvent on jComboBox1 to update jComboBox2 - Keyboard/Mouse-Enter Key conditional

I have two jComboBoxs, (1 and 2)

Based on the selection in 1 it updates 2. The issue I'm facing is that the update on 2 gets done via a database query. So if someone selects the first combobox and starts typing to select what they want, it triggers the database query on every keypress / update to the selection. Which is not ideal.

One method around this is using the ActionEvent to test if it was selected with Mouse or Keyboard.

private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           

    if (evt.getModifiers() == 0) {
        // Do nothing because keyboard is pressed
    } else {
        Object item = jComboBox1.getSelectedItem();
        try{
        // DATABASE CONNECTION HERE
        // Load up jComboBox2
            jComboBox2.removeAllItems();
            while(rs.next())
            {
                jComboBox2.addItem(rs.getString(1));
            } 
            //Close and catch exceptions etc.

Is it possible to have a condition on the }else{ to be able to say

}else if(keyboardpressed(VK_ENTER) or mouseclick) {

The reason being is that users will typically type to select in the first combobox and then press enter to select. Currently they have to reach for the mouse to select.

I would think that you shouldn't allow the query to happen from the 1st combo-box unless the User selects a listed item or hits the ENTER key on a valid text entry. Is there an auto-complete involved with your Combo-Box?. Perhaps even disable the 2nd Combo-Box until a valid choice is made from the 1st Combo-Box

Use the ItemStateChanged event instead:

 private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {                                            
    // Prevent double selection from event.
    if(evt.getStateChange() == ItemEvent.SELECTED) {
        System.out.println(jComboBox1.getSelectedItem().toString());
        // Or whatever you want to do with the selection.
    }
}              

My solution was to use a KeyEvent and an ActionEvent to populate the second comboBox

private void jComboBox1KeyPressed(java.awt.event.KeyEvent evt) {                                      

    if(evt.getKeyCode() == KeyEvent.VK_ENTER) {
        populateRoundNMS();
    }
}                                     

private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           

    if (evt.getModifiers() != 0) {
        populateRoundNMS();
    }
}  

private void populateRoundNMS(){
    //Run SQL and Populate jComboBox2
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM