user3019431
user3019431

Reputation: 11

Updating JComboBox while app is running

Using

list0.setModel(new DefaultComboBoxModel(toTable.data));

I can update the whole JComboBox (list0)... but I want to add a few lines to it (need to have few different positions to choose from on my list). When I'm using this command, it makes an update but everytime in first line of JComboBox. That means I will have only one position in my JComboBox in the end.

I tried

list0.setModel(new DefaultComboBoxModel(toTable.data[x]));

but it's not working. Any ideas?

(x-number of line)

Upvotes: 0

Views: 698

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208964

I'm, not exactly sure what you're asking, but it seems like you just want to add elements dynamically to a JComboBox. You seem to have the right idea, using the DefaultComboBoxModel. To add a new element the list, use

model.addElement(E object)

See DefaulComboBoxModel for more methods.

Here's a simple example. Just type something in the text field, and hit enter. Here's the important code I used

@Override
public void actionPerformed(ActionEvent ae) {
     String text = textField.getText();
     model.addElement(text);
     comboBox.setSelectedItem(text);
     textField.setText("");
}

Here the complete program

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.*;
public class CBoxModelDemo {

    public CBoxModelDemo() {
        JFrame frame = new JFrame("Combo Box Model");

        String[] list = {"Hello 1", "Hello 2", "Hello 3", "Hello 4"};
        final DefaultComboBoxModel model = new DefaultComboBoxModel(list);
        final JComboBox comboBox = new JComboBox(model);
        frame.add(comboBox, BorderLayout.NORTH);

        final JTextField textField = new JTextField(30);
        frame.add(textField, BorderLayout.SOUTH);
        frame.add(new JLabel("Type something, then press enter", JLabel.CENTER));

        textField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                String text = textField.getText();
                model.addElement(text);
                comboBox.setSelectedItem(text);
                textField.setText("");
            }
        });

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new CBoxModelDemo();
            }
        });
    }
}

enter image description here

Upvotes: 3

Related Questions