0

My ScrollPane won't show to my JList. I tried using this, this, and many other ways to add a scroll on my jlist but it wont just show. Here is the sample of my code.

        JScrollPane scrollPane = new JScrollPane(list_1);
    list_1 = new JList();
    scrollPane.setViewportView(list_1);
    list_1.setBounds(16, 94, 579, 248);
    contentPane.add(list_1);
    contentPane.add(scrollPane);

My JList consists of array of files (paths) that came from my database.

Community
  • 1
  • 1
Salvatore
  • 1
  • 1
  • 4
  • Put `JScrollPane scrollPane = new JScrollPane(list_1);` AFTER your `JList` has been created , because it is `null` when you pass it to the `JScrollPane` . – Arnaud Mar 29 '17 at 15:21
  • I have already tried that but still, it's not working – Salvatore Mar 29 '17 at 15:36
  • If you need more help then post a proper [mcve] that demonstrates the problem. So you need a frame with a JList with some data. The whole class should be less than 20 lines of code. – camickr Mar 29 '17 at 15:40

1 Answers1

5

The list needs to be created before being added to the scrollpane. The code should be:

list_1 = new JList();
JScrollPane scrollPane = new JScrollPane(list_1);
//list_1 = new JList();

A component can only have a single parent. The code should be:

//contentPane.add(list_1); // this will remove the list from the scrollpane
contentPane.add(scrollPane);

Don't use setBounds():

list_1.setBounds(16, 94, 579, 248);

The scrollpane uses its own layout manager so the above code does nothing. Swing was designed to be used with layout managers.

3 problems with 6 lines of code. I suggest you start by reading the section from the Swing tutorial on How to Use Lists for more information and working examples.

The tutorial is full of basic Swing information and will help you get started with simple examples containing better structured code.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • I have already tried everything that you have said but it still doesn't work. If I remove the `contentPane.add(list_1);`, nothing will show. – Salvatore Mar 29 '17 at 15:36
  • 1
    @Salvatore, no you haven't tried everything. Did you read the tutorial? Did you download the working examples? Maybe your problem is that you are using a null layout? Read the tutorial, download the working examples and modify that code to do what you want. Start with a working example. If you make a changes and it stops working then you know where the problem is. – camickr Mar 29 '17 at 15:39