javaarraysjlistdefaultlistmodel

How to create several Jlists with different values with DefaultListModel


I have a problem with my code. I have a multidimensional String array[][] and want to create lists out of it. So for each array[] element, I want a new list with it's values. So for example I had 4 lists. List 1 hat 3 values, list 2 had 1 value, list 3 has 4 values and list 4 has 2 values. This worked fine when I just used JList. There I have for each value of the array all of its value.:

    protected static JComponent getButtonCluster() {
    contentPanel.removeAll();
    contentPanel.setLayout(new GridLayout(0,2, 5, 5));
    contentPanel.setBorder(new EmptyBorder(10,0,0,0));
    for (int i=0; i < StringArray.length; i++) {
        listbox = new JList( StringArray[i] );
        contentPanel.add(listbox);
    }
    return contentPanel;
}

But now I had to change from only JLists to DefaultListModel because I want to change the Values by clicking on the Values. And now ALL lists have ALL values of the array. So all 4 boxes have 10 elements.

        final DefaultListModel<String> model = new DefaultListModel<String>();          
        for (int i=0; i < StringArray.length; i++) {
        for (int j=0; j < StringArray[i].length; j++) {
            model.addElement(StringArray[i][j]);

            if((StringArray[i].length -1)== j) {
            listbox = new JList<String>(model);
            contentPanel.add(listbox);

            listbox.addMouseListener(new MouseAdapter() {
                     public void mouseClicked(MouseEvent e) {
                         if (e.getClickCount() == 2) {
                             //Value Change part.......
                          }
                     }
            });
            }
        }

How can I fix my problem so that each list has it's own values?


Solution

  • Previously you were creating a new JList in each pass through your loop. In your new code you're not creating a new model with each pass through the loop so you're just adding more to the existing model every time.