Swing:JPanel "setSize" 被忽略了吗?

Swing: JPanel "setSize" is ignored?

所以在我的程序中,buttonPanel.setSize 似乎不起作用:

public class View extends JFrame {

private JButton[] button = new JButton[16];
private JPanel buttonPanel;

public View() {
    super();
    init();
}

public void init() {
    setTitle("Memory-Game");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(750, 500);
    setResizable(false);
    setLocationRelativeTo(null);
    getContentPane().setLayout(new BorderLayout());

    buttonPanel = new JPanel(new GridLayout(4, 4, 5, 5));
    for (int x = 0; x < 16; x++) {
        button[x] = new JButton();
        buttonPanel.add(button[x]);
    }
    buttonPanel.setSize(315, 315);
    getContentPane().add(buttonPanel, BorderLayout.CENTER);

    setVisible(true);
}

public static void main(String[] args) {
    new View();
}

虽然 JFrame 大小为 750x500,但我希望 buttonPanel 仅在中心占据 space 的 315x315。 但是,buttonPanel 会在整个 JFrame 中延伸。

buttonPanel.setSize(315, 315);

我该如何解决这个问题?

However, the buttonPanel stretches itself across the whole JFrame.

正确。这就是 BorderLayout 的规则。添加到 CENTER 的任何组件都将占用框架中所有可用的 space。

并且 GridLayout 也会增长以占用所有可用的 space。

I want the buttonPanel to only take up space of 315x315 in the center.

不要尝试指定像素大小。这不是布局管理的工作方式。

将组件置于框架中心的最简单方法是使用 GridBagLayout:

//getContentPane().setLayout(new BorderLayout()); // remove
...
//getContentPane().add(buttonPanel, BorderLayout.CENTER); // remove
setLayout( new GridBagLayout() );
add(buttonPanel, new GridBagConstraints());

现在每个按钮都将设置为其首选大小,并且面板的大小将调整为包含所有按钮。

如果您想要额外的 space 按钮,那么您可以使用 属性,例如:

button[x].setMargin( new Insets(20, 20, 20, 20) );

阅读 Layout Mangers 上的 Swing 教程,了解有关每个布局管理器和工作示例的更多信息。

编辑:

the JFrame is set to a specific size and non-resizable. Is there a way to do it with pixels regardless

忘掉框架吧。那不是您使用 Swing 的方式。每个 LAF 上的组件大小可以不同。例如,使用的字体可以不同。标题栏或框架边框的大小可以不同。不要试图设置框架的大小。您为每个组件提供 "hints" 并让每个组件确定其大小。然后你 pack() 的框架和框架将成为 child 组件的大小。

例如,对于按钮,您可以执行以下操作:

button.setPreferredSize( new Dimension(50, 50) );

因此,如果您在网格中有 4 个按钮,则面板的大小将为 (200 x 200)。

如果你想在面板上额外 space 你可以这样做:

panel.setBorder( new EmptyBorder(200, 200, 200, 200) );

这将保留额外 space 到面板的大小,包括按钮现在变成 (400 x 400)。

那么当您 pack() 框架时,框架大小将为 (600 x 600) 加上标题栏和边框的大小。

阅读教程!还有一个关于 How to Use Borders.

的部分