Java Swing:JScrollPane 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10016879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:16:31  来源:igfitidea点击:

Java Swing: JScrollPane not working

javaswingjscrollpane

提问by Reinard

I have a JPanel which contains some fields. The height of the JPanel is limited so I have to put a JScrollPane around it so people can scroll down.

我有一个包含一些字段的 JPanel。JPanel 的高度是有限的,所以我必须在它周围放置一个 JScrollPane,以便人们可以向下滚动。

As you can see below, it displays perfectly. But you can't scroll down (or up).

正如您在下面看到的,它显示完美。但是您不能向下(或向上)滚动。

DetailPanel detail = new DetailPanel();
JScrollPane jsp = new JScrollPane(detail);
jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jsp.setBounds(745, 10, 235, 225);
add(jsp);

Detail panel:

详细信息面板:

private void init(){
            setLayout(null);
            setSize(140, 400);
            int x = 5, y = 0;
            for(int i = 0; i < lbls.length; i++) {
                JLabel lbl = new JLabel(lbls[i]);
                lbl.setBounds(x, y, 200, 25);
                add(lbl);
                fields[i] = new JTextField();
                fields[i].setBounds(x, y+26, 200, 25);
                add(fields[i]);
                y+=50;
            }
        }

enter image description here

在此处输入图片说明

回答by Dan O

Your DetailPanel has no layout manager associated with it, which means it doesn't expand when you add children to it, which means the JScrollPane doesn't have anywhere to scroll. Either call setLayout()on your DetailPanel or override getPreferredSize()to add up the heights of its children and return a meaningful value.

您的 DetailPanel 没有与之关联的布局管理器,这意味着当您向其中添加子项时它不会展开,这意味着 JScrollPane 没有任何地方可以滚动。调用setLayout()您的 DetailPanel 或覆盖getPreferredSize()以将其子项的高度相加并返回一个有意义的值。

回答by CodeBlind

I could be wrong, but I think this might be happening because DetailPanel's layout is null. What happens if you use a BoxLayout in vertical orientation and call detail.setPreferredSize(new Dimension(140,400));?

我可能是错的,但我认为这可能是因为 DetailPanel 的布局为空。如果您在垂直方向使用 BoxLayout 并调用 ,会发生什么detail.setPreferredSize(new Dimension(140,400));