简体   繁体   English

从jList输入的jTextfield

[英]jTextfield with input from jList

I have a jTextfield for which I have to take input from jList. 我有一个jTextfield,我必须从jList接受输入。 On FocusGained property,jList should appear exactly below jTextfield and jList should disappear on FocusLost property. 在FocusGained属性上,jList应该恰好出现在jTextfield的下面,并且jList应该在FocusLost属性上消失。 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. 在FocusGained属性中,出现jList,但在单击它之后,它转到另一个jTextfield的后侧,该字段位于前一个文本字段下方。 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 . 使用JComboBox而不是JTextField You can call JComboBox.setEditable( true ) , and then the JComboBox will have an editor JTextField . 您可以调用JComboBox.setEditable( true ) ,然后JComboBox将具有编辑器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() . 此外,您可以通过调用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. 如果将焦点侦听器添加到JComboBox的编辑器文本字段,则当用户单击文本字段时,还可以从此处显示弹出窗口。 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. 如果您想要一个初始值,可以将其删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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