简体   繁体   中英

JScrollPane not showing up for JList

I'm trying to add a JScrollPane to my JList but for whatever reason it isn't working. I've read several tutorials both on here and other sites and it seems i'm following the directions correctly. I've tried it using both a DefaultListModel and no DefaultListModel seeing if it would make a difference. I've also tried resizing the widget itself and that doesn't work, either.

Here is my code. itemNames is an array of Strings[] which contain various souvenir names that i'm adding to the JList. i'm using BorderLayout() and the panel i'm attempting to add the JScrollPane to is utilizing a GridBagLayout() :

souvenirList = new JList(itemNames);
souvenirList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
souvenirList.setLayoutOrientation(JList.VERTICAL);
souvenirList.setVisibleRowCount(-1);

scrollPane = new JScrollPane(souvenirList);

gbc3.gridx = 1;
gbc3.gridy = 1;
centerPanel.add(scrollPane, gbc3);

c.add(centerPanel, BorderLayout.CENTER);

The box shows up with the names in it, but no JScrollPane :( I was hoping someone could help me out, maybe point out a simple mistake I may be making. Thanks to all in advance. Please don't post links to tutorials on the topic cus believe me, i've read them thoroughly.

EDIT: In this small runnable example I built, using mostly code from my previous snippet, the bar shows up fine! Why could this be? Could it have something to do w the JPanel i'm adding it to? Or maybe the GridBagLayout? I'm so confused here....

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


public class JScroll extends JFrame
{
    JList souvenirList;
    JScrollPane scrollPane;

    Container c = getContentPane();

    private String[] itemNames = {"mug","cap","tee shirt","sweat shirt","pennant","mini stick",
            "bobblehead","paper bag","foam paw","thunderstix"};

    public JScroll()
    {
        setLayout(new FlowLayout());

        souvenirList = new JList(itemNames);
        souvenirList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        souvenirList.setLayoutOrientation(JList.VERTICAL);
        //souvenirList.setVisibleRowCount(-1);

        scrollPane = new JScrollPane(souvenirList);

        c.add(scrollPane);
    }

    public static void main(String[] args)
    {
        JScroll frame = new JScroll();
        frame.setSize(400,300);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

The issue was centered around the fill() method within GridBagLayout() . I didn't notice it was set to VERTICAL , meaning the JList was going to request more vertical space. Changing to HORIZONTAL fixed the issue.

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