JScrollPane does not appear when using it on a JPanel

旧城冷巷雨未停 提交于 2019-12-05 11:15:22

I always have to set the viewport's preferred size like this.

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

public class Example extends JFrame {

    public Example() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        Box box = new Box(BoxLayout.Y_AXIS);
        for (int i = 0; i < 50; i++) {
            box.add(new JButton("Button " + i));
        }
        JScrollPane sp = new JScrollPane(box);
        Dimension d = new Dimension(box.getComponent(0).getPreferredSize());
        sp.getVerticalScrollBar().setUnitIncrement(d.height);
        d.height *= 10; // Show at least 10 buttons
        sp.getViewport().setPreferredSize(d);

        add(sp, BorderLayout.CENTER);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                Example e = new Example();
            }
        });
    }
}

Don't set any sizes! The scroll-bar appears if this change is made.

JPanel panTopCenter = new JPanel(new GridLayout());

The basic problem is that FlowLayout will show components at the smallest size needed to display it, and for a scroll-pane, that is (decided to be) 0x0. By using a GridLayout with no arguments in the constructor and adding the scroll-pane as the only component, it will be forced to fill the available space.

mKorbel

You have to set the preferred-size, in the case that JScrollPane is single JComponent in the container or top-level container.

scrollPane.setPreferredSize(new Dimension(100,500));

Better would be to use GridLayout for the same type of JComponents.

The best solution, quick and easy, is using JXPanel from SwingX, which is quasi-standard and implements Scrollable.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!