Suavi
Suavi

Reputation: 9

How can I get value from JTextField to JComboBox?

There are 2 JTextField components and 1 JComboBox in my project.

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:

combobox 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]

Upvotes: 0

Views: 424

Answers (2)

Dhyey Shah
Dhyey Shah

Reputation: 652

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.

Your code would be like:

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

Upvotes: 1

Jonatas Emidio
Jonatas Emidio

Reputation: 73

Each time that your "t1" is changed you will add another item on your combo.

Instead of adding a listener in your textfield, you can add a FocusListener in your combo. 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);
        }
    });

Upvotes: 0

Related Questions