Question

I have a textfield that when gets Focus shows a panel with a table and when Focus lost makes it invisible.

Typing into the field searches the database alongside and displays the results in table.

When I click on the table to select a row, the text field loses focus and then instantly gains it again and I am not able to select a row (row selection - enabled, cell editing - disabled, Selection Mode - Single Selection)

Code for When TextField Gains and Loses Focus & when typing:

private void productBrandTextFieldFocusGained(java.awt.event.FocusEvent evt) {                                                  
    brandSearchPanel.setVisible(true);
    displayBrands();
} 

private void productBrandTextFieldFocusLost(java.awt.event.FocusEvent evt) {                                                
    brandSearchPanel.setVisible(false);
}

private void productBrandTextFieldKeyReleased(java.awt.event.KeyEvent evt) {                                                  
    searchBrand();                           
}   

Images showing what happens when Focus is Gained, Lost or Typing @ http://sdrv.ms/14TEq2T

Also, I would like to be able to go through the rows using the DOWN Key. Please suggest some code that when Down key is pressed the focus is lost from textfield and row is selected and pressing UP OR DOWN key will go up or down the rows.

Was it helpful?

Solution

The FocusEvent has a method getOppositeComponent() that you might be able to use in your logic.

When the text field loses focus you invoke this method. If the component gaining focus is the table, then you don't make the table panel invisible. Then when the user clicks on the table focus should stay there.

To handle the Up/Down arrow keys from the text field you would need to use Key Bindings. You would create an Action that gets the current selection from the table and then changes the selection by +/- 1 depending on the key that was pressed. Read the Swing tutorial on How to Use Key Bindings for more information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top