javaswingjscrollpanejlistdefaultlistmodel

Cannot add to a JList when list is added to a JScrollPane


I wrote a program which select files and adds them to a JList. The program works fine, and the code to add the files to the list is like this:

JPanel pane;
File newFile[];
static List<File> files = new ArrayList<File>();
static DefaultListModel<File> listModel = new DefaultListModel<>();
JList<File> fileList = new JList<>(listModel);

JPanel listPane = new JPanel();
pane.add(listPane, BorderLayout.CENTER);
listPane.setBackground(Color.LIGHT_GRAY);
listPane.setBorder(new EmptyBorder(0, 20, 0, 0));
listPane.setLayout(new BorderLayout());
listPane.add(fileList);
}
void getFile() {
    final JFileChooser fc = new JFileChooser();
    fc.setDialogTitle("Select File...");
    fc.setApproveButtonText("Select");
    fc.setMultiSelectionEnabled(true);
    int returnVal = fc.showOpenDialog(pane);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        newFile = fc.getSelectedFiles();
    }
}
void setFile() {
    int i = 0;
    while (i < newFile.length) {
        files.add(newFile[i]);
        listModel.addElement(newFile[i]);
        i++;
    }
}

This is the base code for selecting and adding the files. So now I want to have a scrollbar on the pane, so I modified it to a JScrollPane like this:

JScrollPane listPane = new JScrollPane();
pane.add(listPane, BorderLayout.CENTER);
listPane.setBackground(Color.LIGHT_GRAY);
listPane.setBorder(new EmptyBorder(0, 20, 0, 0));
listPane.setViewportView(fileList);
listPane.add(fileList);
}

So everything compiles without errors, but nothing is added to the JScrollPane. It is my understanding that a JScrollPane can be used like a regular JPanel, except it will have scrollbars when overflowed. Is there something about JScrollPanes that I am missing here?


Solution

  • try removing

    listPane.add(fileList); //remove
    

    you should use setViewportView() method to add a component to scrollpane.and you have done it.so you don't need to add again by calling listPane.add .

    example

    JScrollPane listPane = new JScrollPane();
    pane.add(listPane, BorderLayout.CENTER);
    listPane.setBackground(Color.LIGHT_GRAY);
    listPane.setBorder(new EmptyBorder(0, 20, 0, 0));
    listPane.setViewportView(fileList);
    // removed add line
    

    also you can pass component that you want to add to scrollpane by passing to scroll pane constructor as thompson said.

    JScrollPane listPane = new JScrollPane(fileList);
    

    also as thompson said you should avoid declaring listModel ,files .you should read more about static keyword and when you should use it .