简体   繁体   中英

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
}

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.

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