Question

Is there a purpose of using:

add(new JScrollPane(list)) instead of add(list) in the code below?

public class Gui extends JFrame {

    private JList list;
    private static String[] colorNames = {"black", "blue", "red", "white"};
    private static Color[] colors = {Color.BLACK, Color.BLUE, Color.RED, Color.WHITE};

    Gui() {
        list = new JList(colorNames);
        list.setVisibleRowCount(colorNames.length);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        **add(new JScrollPane(list))**;


    }
}
Was it helpful?

Solution

Being truly objective to your original question, the answer would be: it depends on what you wish to achieve in your UI display.

However, in the vast majority of cases I should imagine that wrapping components such as JLists in a JScrollPane will be a good idea.

JScrollPanes exist to help when a particular JComponent is essentially too large to fit in its assigned space. With a JList if the number of items exceeds the available height of the JList itself then you'll lose sight of those items. Wrapping in a JScrollPane will provide the scrolling mechanism for the user to browse by scrolling all available items.

Of course, if your list doesn't exceed its available space then no harm is done by having it in a JScrollPane. (Plus you can customise its display so that it doesn't display scrollbars until necessary, for example.)

It's especially common to use JScrollPane in conjunction with JLists, JTable and JTextArea. Don't be fooled by JComboBox though - that has its own scrolling mechanism.

The official Swing tutorial has a section called How to Use Scroll Panes which provides detailed information.

OTHER TIPS

Yes - if the contents of the list extend beyond the visible window, a JScrollPane will, not surprisingly, automatically add the scroll bars for you.

If you only add the list, it will be functionally the same unless the area is too small to display the full list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top