简体   繁体   中英

Add scroll on my JList

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.

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.

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