John Smith
John Smith

Reputation: 6207

JScrollPane not working on JList

code:

list1items = new DefaultListModel();
list1items.addElement("-");
list1 = new JList(list1items);
list1.setSelectionMode (ListSelectionModel.SINGLE_SELECTION);
list1.setBounds(0,0, 100,100);
JScrollPane list1scr = new JScrollPane(list1);
list1scr.setPreferredSize(new Dimension(20, 20));
list1.setVisibleRowCount(8);
getContentPane().add (list1scr);

And no scroll-bar appears. When there are too many items, they are hidden, I cant reach them. How to solve this?

Upvotes: 1

Views: 5566

Answers (2)

Nick Rippe
Nick Rippe

Reputation: 6475

To expand on Michael Ardan's answer, you were adding you JList to the panel instead of the JScrollPane. The JScrollPane must be added to the panel and the JList must be added to the ScrollPane for it to work. There's really no need to use setBounds or setPreferredSize - get rid of them. JList takes care of all that when you call the setVisibleRowCount method. Here's an example of your ScrollPane working. If you still have problems, plug your own code into this example until it breaks. Then tell us what broke it. If not, accept Michael's answer.

import java.awt.*;
import javax.swing.*;

public class Temp extends JPanel{
    public Temp(){

        DefaultListModel list1items = new DefaultListModel();
        list1items.addElement("-");
        for(int i = 0; i < 200; i++)
            list1items.addElement("Item " + i);
        JList list1 = new JList(list1items);
        list1.setSelectionMode (ListSelectionModel.SINGLE_SELECTION);
        JScrollPane list1scr = new JScrollPane(list1);
        list1.setVisibleRowCount(8);
        add (list1scr);
    }


    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new Temp());
        frame.pack();
        frame.setVisible(true);
    }
}

Upvotes: 5

getContentPane().add(list1scr);

Upvotes: 10

Related Questions