简体   繁体   English

我如何从JTextField到JComboBox获得价值?

[英]How can I get value from JTextField to JComboBox?

There are 2 JTextField components and 1 JComboBox in my project. 我的项目中有2个JTextField组件和1个JComboBox

When I input data to text fields, the combo box is adding separate items/row for each letter or number. 当我在文本字段中输入数据时,组合框将为每个字母或数字添加单独的项目/行。

How can I fix that? 我该如何解决?

See the picture: 看图片:

组合框图片

Here's my code: 这是我的代码:

t1.getDocument().addDocumentListener(new DocumentListener() {
          public void changedUpdate(DocumentEvent e) {
           changed();
          }
          public void removeUpdate(DocumentEvent e) {
           changed();
          }
          public void insertUpdate(DocumentEvent e) {
            changed();
        }

        public void changed() {
            if (!t1.getText().trim().isEmpty())
            {
                c1.addItem(t1.getText());
                }
          }
        });
    [Combobox adding separate row][1]

According to what i understand from your problem,you want to add items into your combobox, once the user completes entering the full item name. 根据我对您的问题的了解,一旦用户完成输入完整的项目名称,便想将项目添加到组合框中。 For this: 为了这:

Remove your document listener and instead use actionListener which is triggered automatically when a user presses enter. 删除您的文档侦听器,而是使用actionListener,该行为将在用户按下Enter键时自动触发。

Your code would be like: 您的代码如下:

t1.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e){
         if (!t1.getText().trim().isEmpty())
             c1.addItem(t1.getText());
    }
});

Each time that your "t1" is changed you will add another item on your combo. 每次更改“ t1”时,您都会在组合中添加另一个项目。

Instead of adding a listener in your textfield, you can add a FocusListener in your combo. 可以在组合中添加FocusListener,而不是在文本字段中添加侦听器。 There you will be able to get the textfield content and add in your menu in the open process. 在那里,您将能够获取文本字段的内容并在打开过程中添加菜单。

You can do something like (maybe it is not the best option but will work): 您可以做类似的事情(也许这不是最好的选择,但是会起作用):

        c1.addFocusListener(new FocusListener() {

        @Override
        public void focusLost(FocusEvent e) {}

        @Override
        public void focusGained(FocusEvent e) {
            c1.addItem(t1.getText);
        }
    });

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

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