简体   繁体   中英

Simple Jlist Topic Board

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 DefaultListModel s, 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.

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);
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM