简体   繁体   中英

JScrollPane doesn't work for my JList as well as setVisibleRowCount(4);

I've wanted to have 4 visible rows out of available 8 but the code doesn't seem to work. I've tried different approaches but it just doesn't let me do it. It keeps showing me 8 of them. Second issue is that JScrollPane doesn't work for the JList too. There is no scroll next to the Jlist. This is part of my code responsible for Jlist. Maybe you will be able to point out any mistakes I've done. Here's my code:

    //--------List--------------------------------      
    String[] planets = {"Mercury", "Venus", "Earth", "Mars",
            "Jupiter", "Saturn", "Neptune", "Uranus"};
    JList<String> planetsList = new JList<String>(planets);
    planetsList.setToolTipText("A list with various planets");
    planetsList.setVisibleRowCount(4);
    JScrollPane listScroller = new JScrollPane(planetsList);

    JPanel bottom = new JPanel();
    bottom.add(planetsList);
    this.add(bottom, BorderLayout.SOUTH);

Instead of adding Jlist object add JScrollPane object to JPanel

bottom.add(listScroller);

Full Code

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class PanelListScroll extends JPanel {

    public PanelListScroll() {

        String[] planets = { "Mercury", "Venus", "Earth", "Mars", "Jupiter",
                "Saturn", "Neptune", "Uranus" };

        JList<String> planetsList = new JList<String>(planets);
        planetsList.setToolTipText("A list with various planets");
        planetsList.setVisibleRowCount(4);
        JScrollPane listScroller = new JScrollPane(planetsList);

        JPanel bottom = new JPanel();

        bottom.add(listScroller);
        add(bottom, BorderLayout.SOUTH);

    }

    public static void main(String[] a) {

        JFrame jf = new JFrame();
        PanelListScroll tab = new PanelListScroll();
        jf.setTitle("JList");
        jf.setSize(200, 200);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.add(tab);

    }

}

Output:

在此输入图像描述

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