简体   繁体   English

Java:JButton数组不会改变大小

[英]Java: JButton array won't change size

Hey I made 3 for loops to create 3 different arrays of JButtons. 嘿,我做了3个for循环来创建3个不同的JButtons数组。 Which I then put into a Gridlayout. 然后将其放入Gridlayout。 The left and the right side turn out fine but the center will just fill the panel. 左侧和右侧都很好,但中央只会填充面板。

Here is my code for the right side: 这是我右侧的代码:

        rightPanel = new JPanel();
    rightPanel.setLayout(new GridLayout(12, 4, 5, 5));
    rightPanel.setBorder(new EmptyBorder(10 ,10 ,10 ,10));


    for (int a = 0; a < 12; a++) {
        for (int b = 0; b < 4; b++) {
            battons[b][a] = new feedbackKnop.RechterKnop();
            battons[b][a].setPreferredSize(new Dimension(50, 50));
            rightPanel.add(battons[b][a]);
            battons[b][a].setEnabled(false);
        }
    }

Here is my code for the center: 这是我的中心代码:

        btnPanel = new JPanel();
    btnPanel.setLayout(new GridLayout(12, 4, 5, 5));
    btnPanel.setBorder(new EmptyBorder(10 ,10 ,10 ,10));

    for (int i = 0; i < 12; i++) {
        for (int j = 0; j < 4; j++) {
            buttons[j][i] = new KleurenButton("");
            buttons[j][i].setPreferredSize(new Dimension (50, 50));
            btnPanel.add(buttons[j][i]);
            buttons[j][i].setEnabled(false);

        }

    }

I want it to have the size like the circles on the right side 我希望它的大小像右侧的圆圈一样

Result: 结果:

结果

The GridLayout causes all grids to be the same size, and the BorderLayout expands the center to fill the window. GridLayout使所有网格具有相同的大小,并且BorderLayout扩展中心以填充窗口。 To fix this you need to either enforce the Window Size to be fixed (or at a certain aspect ratio), or pick a different layout that doesn't automatically expand it's components. 要解决此问题,您需要强制固定“窗口大小”(或以特定的宽高比),或者选择不会自动扩展其组件的其他布局。 GroupLayout is very popular. GroupLayout非常受欢迎。

As commenters have suggested, it is an issue with BorderLayout. 正如评论者所建议的那样,这是BorderLayout的问题。 BorderLayout has a "greedy" CENTER panel, meaning that by default it will stretch whatever JComponent is in there to the entire size. BorderLayout具有一个“贪心”的CENTER面板,这意味着默认情况下,它将把其中的JComponent拉伸到整个大小。 This is unlike the borders (NORTH, SOUTH, etc.) that will use a preferredSize. 这与将使用preferredSize的边框(NORTH,SOUTH等)不同。 That's why your right and left panels are not streched. 这就是为什么您的左右面板不张紧的原因。

A simple solution (without drastic changes to your layouts) might be to add a JPanel to the center, give it a FlowLayout, and then add your Center Grid Panel to that. 一个简单的解决方案(无需对布局进行大幅度更改)可能是将JPanel添加到中心,为其提供FlowLayout,然后在其中添加“中心网格”面板。 It's not ideal, but might be a quick way to prototype your view. 这不是理想的方法,但是它可能是快速创建视图原型的快速方法。

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

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