繁体   English   中英

Java JScrollPane和FlowLayout

[英]Java JScrollPane and FlowLayout

在昨天从该站点上的用户那里获得了如此巨大的帮助之后,我决定在这里再问一个问题,希望你们能为我提供帮助。 我想编写一个包含组件的框架,它们需要在JPanel上 ,而JPanel应该在JScrollPane中

现在,问题是我需要为面板使用FlowLayout ,因为我不知道面板中将有多少个组件。

如果我在JScrollPane中使用FlowLayout ,它不会创建新行,而只会水平移动,这在实际应用程序中看起来很奇怪。 我要的是,如果窗口结束了,就要换一行。

问题是如何解决这个问题。 我不能放置PreferredSize,因为垂直ScrollBar不会比我放置PreferredSize更远,所以我真的不知道该怎么做...也许会更改布局? 我将不胜感激任何帮助!

问题的示例代码:

public class scroller extends JFrame {

    Container c;
    JPanel p;
    JScrollPane pane;
    JButton button1;
    JButton button2;
    JButton button3;
    JButton button4;

    public scroller() {
        c = getContentPane();
        c.setLayout(new BorderLayout());
        p = new JPanel();
        p.setLayout(new FlowLayout());
        pane = new JScrollPane(p);
        button1 = new JButton("OK1");
        p.add(button1);
        button2 = new JButton("OK2");
        p.add(button2);
        button3 = new JButton("OK3");
        p.add(button3);
        button4 = new JButton("OK4");
        p.add(button4);
        p.setVisible(true);
        c.add(pane,BorderLayout.CENTER);

    }

    public static void main(String[] args) {
        scroller window = new scroller();
        window.setSize(200,200);
        window.setVisible(true);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    }   
}

我不能放置PreferredSize,因为垂直ScrollBar不会比我放置PreferredSize更远

正确,在将组件添加到面板时,需要动态计算preferredSize()。 FlowLayout的默认首选大小计算假定组件为单行。

因此,解决方案是使用其他布局管理器。

WrapLayout扩展了FlowLayout并覆盖了首选的尺寸计算,以在组件换行到新行时提供首选的宽度和高度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM