繁体   English   中英

防止 JScrollPane 中的 JPanel 水平增长

[英]Prevent JPanel within JScrollPane from growing horizontally

我有一个带有 FlowLayout 的 JPanel,我正在用相同的组件(MWE 中的 JButtons)动态填充它。 JPanel 位于 JScrollPane 内。 当我添加组件时,我希望它们从左到右填充,一旦顶行变得比 JScrollPane 宽,就向下一行填充。

我的问题是 FlowLayout 反而扩大了 JPanel ad nauseum,JScrollPane 通过添加水平滚动来响应。 我如何防止这种情况?

编辑:我见过 WrapLayout; 我希望在标准 Java 中找到解决方案,因为我在我的应用程序中使用了 NetBeans GUI Builder。

MWE 基于这个答案

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

public class MWE extends JFrame implements ActionListener {

    JPanel panel;
    JScrollPane pane;

    public MWE() {
        super("Add component on JFrame at runtime");
        setLayout(new BorderLayout());

        this.panel = new JPanel();
        this.pane = new JScrollPane();
        this.panel.setLayout(new FlowLayout(FlowLayout.LEFT));
        this.pane.setViewportView(this.panel);
        add(pane, BorderLayout.CENTER);

        JButton button = new JButton("CLICK HERE");
        add(button, BorderLayout.SOUTH);
        button.addActionListener(this);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500, 500);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent evt) {
        this.panel.add(new JButton("Button"));
        this.panel.revalidate();
        validate();
    }

    public static void main(String[] args) {
        MWE mwe = new MWE();
    }
}

尝试为面板设置首选尺寸:

this.panel.setPreferredSize(new Dimension(500, 500));

暂无
暂无

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

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