-1

Here is my code to create a Jlist and filling it up using action listener

At the first place I used an array of string to fill up the Jlist and I had scroller. Then for upating Jlist I need to change the mode of the Jlist to DefaultListModel and as soon as I did that change I lost my scroller.

I donot know what went wrong

Can any one help me please

private Component makeListView() {  
        final DefaultListModel<String> listModel = new DefaultListModel<String>();
        final JList<String> list = new JList<String>(listModel);
        list.setModel(listModel);
        updateCourseListPanel(listModel);
        notifyObserverInModelForClickingOnListItem(list);       
        list.setPreferredSize(getSize());
        list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
        list.setVisibleRowCount(-1);        
        list.setFixedCellWidth(80);
        JScrollPane listScroller = new JScrollPane(list);
        listScroller.setPreferredSize(getMaximumSize());
        setVisible(true);       
        return list;
    }
kleopatra
  • 51,061
  • 28
  • 99
  • 211
user2277918
  • 237
  • 2
  • 3
  • 8

1 Answers1

2

hard to tell from your snippet (as you didn't show the code that calls it): on face value, the issue is that you return the list instead of the scrollPane it's added to.

The deeper issue is that you seem to (guessing only, though, for lack of details :-) re-create the list whenever the data needs to be updated. A better approach is to separate the creation of the list and its model from its update and only update the model as needed:

private Component makeListView() {  
    final DefaultListModel<String> listModel = new DefaultListModel<String>();
    final JList<String> list = new JList<String>(listModel);
    list.setModel(listModel);
    list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
    list.setFixedCellWidth(80);
    JScrollPane listScroller = new JScrollPane(list);
    return listScroller;
 }

 private void update(Jlist list) {  
    updateCourseListPanel(list.getModel());
    notifyObserverInModelForClickingOnListItem(list);       
 }

BTW, never-ever call any of the setXXSize methods, some reasons

Community
  • 1
  • 1
kleopatra
  • 51,061
  • 28
  • 99
  • 211