StReeTzZz
StReeTzZz

Reputation: 17

Check JComboBox Value

I need to create a new method to check the value of the selected item in combo box. That combo box is populated from database.

This is how get the selected item:

 combo.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {

    String x=(String) combo.getSelectedItem();

The string "x" save the value of selected item because I need to use "x" in my other query.

    ResultSet st = stt.executeQuery("Select Name from Table where Number="+x+"");

With that query I can populate the JList.

The problem is, when I select another item in combo box, the list does not update. So I need to create another statement to check the combo box value? If yes, how?

Upvotes: 1

Views: 2058

Answers (1)

trashgod
trashgod

Reputation: 205875

Let your JList use a ListModel that also implements ActionListener. Add this specialized listener to the combo. Each time the combo changes, your ListModel's action listener will be invoked. In the listener, you can update the ListModel in place.

Addendum: Here's the basic approach.

enter image description here

/**
 * @see http://stackoverflow.com/a/16587357/230513
 */
public class ListListenerTest {

    private static final String[] items = new String[]{"1", "2", "3"};
    private JComboBox combo = new JComboBox(items);
    private JList list = new JList(new MyModel(combo));

    private static class MyModel extends DefaultListModel implements ActionListener {

        private JComboBox combo;

        public MyModel(JComboBox combo) {
            this.combo = combo;
            addElement(combo.getSelectedItem());
            combo.addActionListener(this);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            set(0, combo.getSelectedItem());
            System.out.println("Combo changed.");
        }
    }

    private void display() {
        JFrame f = new JFrame("ListListenerTest");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLayout(new GridLayout(1, 0));
        f.add(combo);
        f.add(list);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ListListenerTest().display();
            }
        });
    }
}

Upvotes: 2

Related Questions