Ajinkya Jagtap
Ajinkya Jagtap

Reputation: 19

jTextfield with input from jList

I have a jTextfield for which I have to take input from jList. On FocusGained property,jList should appear exactly below jTextfield and jList should disappear on FocusLost property. I have done some coding but I am getting a problem in it. At FocusGained property,jList appears but aftr clicking on it, it goes to back side of other jTextfield which is below previous textfield. Following is my Code:

private void txtAccountFocusGained(java.awt.event.FocusEvent evt) {                                       
    jScrollPane3.setLocation(txtAccount.getX(), txtAccount.getY()+txtAccount.getHeight());
    jScrollPane3.setVisible(true);    //scrollpane associated with list
    listAccount.setVisible(true);   //listAccount is jList
}

private void listAccountMouseClicked(java.awt.event.MouseEvent evt) {                                         
    txtAccount.setText((String)listAccount.getSelectedValue());
    jScrollPane3.setVisible(false);  //scrollpane associated with list
    txtSalesLedger.requestFocus(); //it is next field
}

Upvotes: 0

Views: 934

Answers (1)

icza
icza

Reputation: 418377

Use a JComboBox instead of a JTextField. You can call JComboBox.setEditable( true ), and then the JComboBox will have an editor JTextField. Exactly what you want, and the user can enter any text, but also the list box can be opened with the arrow icon. Moreover you can make the list automatically appear by calling JComboBox.showPopup(). If you add a focus listener to the JComboBox's editor text field, you can also show the popup from there when the user clicks on the text field. The popup list can be closed with the arrow icon.

Here's a sample code:

final JComboBox comboBox = new JComboBox( 
    new Object[] { "", "Item #1", "Another item", "Something else" } );

comboBox.setEditable( true );

comboBox.getEditor().getEditorComponent().addFocusListener( new FocusAdapter() {
    @Override
    public void focusGained( final FocusEvent event ) {
        comboBox.showPopup();
    }
} );

Note: The first item of the combo box is an empty string. I added that so that the editor text field of the combo box will not show any value initially. You can remove that if you want an initial value of course.

Upvotes: 1

Related Questions