K
K
Kostya Bakay2015-03-13 03:54:17
Java
Kostya Bakay, 2015-03-13 03:54:17

How to make a dependency between multiple JList?

The essence is this - there is one JList, which stores a list of operations for selection (top up a mobile account, pay for the Internet ...). If I choose to top up a mobile account in the list, then how can I do it correctly so that after this choice in another JList (located nearby), the necessary list elements are selected (in this case, a list of mobile operators, when choosing to pay for the Internet at the beginning, there will be other list elements) ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
exenza, 2015-03-13
@kostyabakay

Something like this?

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;

class ListExample extends JFrame {

    private JPanel topPanel;
    private JList mainList;
    JList slaveList;

    public ListExample() {

        setTitle("Simple ListBox Application");
        setSize(300, 100);
        setBackground(Color.gray);
        topPanel = new JPanel();
        topPanel.setLayout(new FlowLayout());
        getContentPane().add(topPanel);

        mainList = new JList(new String [] {"water", "fire", "wind"});
        mainList.setSelectedIndex(0);
        slaveList = new JList(new String [] {"water", "water", "water"});
        MyListener myListener = new MyListener();
        mainList.addListSelectionListener(myListener);
        topPanel.add(mainList);
        topPanel.add(slaveList);
    }

    public static void main(String args[]) {
        ListExample mainFrame = new ListExample();
        mainFrame.setVisible( true );
    }

    class MyListener implements ListSelectionListener {

        String [] list;

        public void valueChanged(ListSelectionEvent evt) {
            if (evt.getValueIsAdjusting()) {
                JList list = (JList) evt.getSource();
                int value = list.getSelectedIndex();
                switch (value) {
                case 0:
                    this.list = new String[] {"water", "water", "water"};
                    break;
                case 1:
                    this.list = new String[] {"fire", "fire", "fire"};
                    break;
                case 2:
                    this.list = new String[] {"wind", "wind", "wind"};
                    break;
                }
                slaveList.setListData(this.list);
            }
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question