Simple Jlist Topic Board

92 views Asked by At

So I am currently attempting to create a simple Javaspace Topic Board as a side project, to do this I have a basic intereface that allows for Topics and messages to be added from a text field into two seperate DefaultListModels, my questions is this:

Is there any way when selecting an element from Jlist1 using a selectionlistener, to open an instance of Jlist2 for that specific element? This must then display messages for the topic in Jlist1, selecting another topic in Jlist1 would have the same effect vice versa.

I apologize for the lack of code, this is due to technical issues regarding a small child, juice and my old system.

1

There are 1 answers

0
Jirka On

How about this? You listen to selection in the first list, and change the model of the second list based on that:

public class AbcFrame extends javax.swing.JFrame {
    // map linking items in the first lists with items in the second list
    private final Map<String,ListModel> map = new HashMap<>();
    private javax.swing.JList jList1;
    private javax.swing.JList jList2;

    public AbcFrame() {
        initComponents();   // create and place the lists in the frame

        map.put("itemA", new MyListModel(Arrays.asList("a_1", "a_2", "a_3")));
        map.put("itemB", new MyListModel(Arrays.asList("b_1", "b_2")));

        jList1.setModel(new MyListModel(Arrays.asList("itemA", "itemB")));

        // when the selection of the first list changes, change the model of the second list
        jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                String item = (String) jList1.getSelectedValue();
                ListModel model2 = map.get(item);
                jList2.setModel(model2);
            }
        });
    }

    private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {                                    
        String item = (String) jList1.getSelectedValue();
        ListModel model2 = map.get(item);
        jList2.setModel(model2);

    }                                   

    // a simple list model wrapping a java.util.List
    private static class MyListModel extends AbstractListModel {
        private final java.util.List<String> items;

        public MyListModel(java.util.List<String> items) {
            this.items = items;
        }

        @Override
        public int getSize() {
            return items.size();
        }

        @Override
        public Object getElementAt(int index) {
            return items.get(index);
        }
    }

}