如何使用嵌套在ScrollPane

时间:2016-03-01 20:09:12

标签: 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");

1 个答案:

答案 0 :(得分:0)

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

之后,在您达到该号码之前,您可以通过以下方式添加按钮:

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

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

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

最后,用剩下的按钮填充第二行。

panel.add(btnButton_X, "grow");