java - 如何使用嵌套在 ScrollPane 内的 MigLayout 组织两行大小相同的按钮

标签 java jframe jscrollpane miglayout

我正在使用 JFrame 并尝试设计一个容器,该容器可以容纳分布在 2 行(和多列)上的按钮数组。

我需要安装尽可能多的按钮。虽然文本宽度不同,但按钮本身的大小必须相同(如果文本大于宽度,则文本必须包裹在按钮内)。

我正在使用 JScrollPane,并使用 MigLayout 布局按钮。

这是我到目前为止的代码。我是 MigLayout 的新手,有太多选项让我很快就感到困惑。我需要帮助设置行/列约束,以便我只有两行(并且列数将等于数组大小的一半),并设置组件约束,以便每个按钮具有相同的宽度、高度和换行文本。

我在这里手动添加按钮,因为我还没有使用数组来实现它。

更新:我能够弄清楚如何使文本换行,就像我想要使用 HTML 标签一样。

    JPanel panel = new JPanel(new MigLayout("", "[300px]", "[150px]"));
    panel.setBounds(35, 377, 1294, 307);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(10, 377, 1319, 341);
    scrollPane.setViewportView(panel);
    contentPane.add(scrollPane);

    JButton btnButton = new JButton("The dominoes will help you read what's written behind the board.");
    panel.add(btnButton, "cell 0 0,grow");

    JButton btnButton_1 = new JButton("What about the wooden box?");
    panel.add(btnButton_1, "cell 1 0,grow");

    JButton btnButton_2 = new JButton("Did you look at the stool?");
    panel.add(btnButton_2, "cell 2 0,grow");

    JButton btnButton_3 = new JButton("The dominoes will help you read what's written behind the board.");
    panel.add(btnButton_3, "cell 3 0,grow");

    JButton btnButton_4 = new JButton("The room is a clock.");
    panel.add(btnButton_4, "cell 4 0,grow");

    JButton btnButton_5 = new JButton("If 12:00 is the red dot, where is 6:05?");
    panel.add(btnButton_5, "cell 5 0,grow");

    JButton btnButton_6 = new JButton("Sunglasses are black.");
    panel.add(btnButton_6, "cell 0 1,grow");

    JButton btnButton_7 = new JButton("Are you sure you looked everywhere?");
    panel.add(btnButton_7, "cell 1 1,grow");

    JButton btnButton_8 = new JButton("The darts are color coded.");
    panel.add(btnButton_8, "cell 2 1,grow");

    JButton btnButton_9 = new JButton("Where else have you seen this pattern?");
    panel.add(btnButton_9, "cell 3 1,grow");

    JButton btnButton_10 = new JButton("Did you look are the wigs?");
    panel.add(btnButton_10, "cell 4 1,grow");

    JButton btnButton_11 = new JButton("Maybe they're page numbers?");
    panel.add(btnButton_11, "cell 5 1,grow");

最佳答案

所以,你知道你有 2 行 N 列。我想您知道需要添加的按钮总数,您应该除以行数以获得按行的按钮数。

之后,直到达到该数字,您可以通过以下方式添加按钮:

while (anyCounter < totalButtonsByRow) {
    panel.add(btnButton_X, "grow");
    anyCounter++;
}

请考虑到,当您达到一行中的按钮数量时,请按以下方式添加最后一个按钮:

panel.add(btnButton_X, "grow, wrap");

最后,用其余按钮填充第二行。

panel.add(btnButton_X, "grow");

关于java - 如何使用嵌套在 ScrollPane 内的 MigLayout 组织两行大小相同的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35732462/

相关文章:

java - 如何设置 JScrollPane 的大小和位置?

Java: block 增量和单位增量有什么区别,这些值有什么用?

java - 是否需要为这种 Mockito 情况编写自定义匹配器?

java - 文件程序显示错误

java - Logback 不创建输出日志文件

java - 如何在 JPanel 上将 double 或 float 显示为仅小数点后两位

java - 使用 ScrollPane java 的动态按钮

java - 如何根据用户输入将数组中最大的元素放在末尾,最小的元素放在开头?

java - 在Jframe中添加循环

Java swing setMaximumSize 不工作