如何修复 GUI 组件 "leaving" 它们的面板或占用更多 space 它们应该占用的空间?

How to fix GUI components "leaving" their panels or taking up more space they they are supposed to?

我正在尝试为游戏制作 GUI。我对 Java 非常陌生,尤其是 GUI。下面的代码是一个片段,它应该制作一个 JFrame 带有用于组织的嵌套面板。它一直有效,直到我将按钮添加到按钮面板。他们最终出现在 boardBckg 面板上。如果我设法将它们放在正确的面板上,JTextField 就会消失或占据整个屏幕。这两天我一直在研究这部分代码,我真的可以使用GUI提示。

private void makeWindow()
    {

    boardPanel = new JPanel();
    boardBckg = new JPanel();
    menuPanel = new JPanel();
    save = new JButton("Save");
    save.setSize(Buttons);
    load = new JButton("Load");
    load.setSize(Buttons);
    replay = new JButton ("Replay");
    replay.setSize(Buttons);
    words = new JTextField();

    frame = new JFrame(title);

    boardPanel.setSize(PANEL);
    boardPanel.setMaximumSize(MAX);
    boardPanel.setMinimumSize(MIN);
    boardPanel.setLayout(new GridLayout(m,n));
    boardBckg.setSize(1000, 1000);
    boardBckg.setBackground(Color.cyan);
    boardBckg.add(boardPanel, BorderLayout.CENTER);

    frame.setSize(1500, 1000);
    frame.setResizable(false);
    frame.setVisible(true);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    BoxLayout vertical = new BoxLayout(menuPanel, BoxLayout.Y_AXIS);

    menuPanel.setSize(500, 1000);
    menuPanel.setBackground(Color.blue);
    menuPanel.setLayout(vertical);
    frame.add(boardBckg);
    frame.add(menuPanel);
    JPanel iGiveUp = new JPanel();
    iGiveUp.setBackground(Color.black);
    JPanel buttons = new JPanel();
    buttons.setBackground(Color.darkGray);
    buttons.add(save);
    buttons.add(load);
    buttons.add(replay);

    menuPanel.add(iGiveUp);

    menuPanel.add(buttons);
    iGiveUp.add(words);
boardBckg.add(boardPanel, BorderLayout.CENTER);

JPanel 的默认布局是 FlowLayout。将组件添加到面板时不能只指定 BorderLayout 约束。

frame.add(boardBckg);
frame.add(menuPanel);

框架(的内容窗格)的默认布局是 BorderLayout。如果您不指定约束,则该组件将添加到 BorderLayout.CENTER。问题是只能将一个组件添加到中心,因此您只能看到最后添加的组件。

frame.setVisible(true);

应在框架打包并显示之前将组件添加到框架中。所以上面的语句应该是构造函数中的最后一条语句。

我不知道你想要的布局是什么,但你需要从简单的开始,并利用框架的默认 BorderLayout。

所以你的基本逻辑可能是这样的:

JPanel menuPanel = new JPanel()
menuPanel.setLayout(new BoxLayout(menuPanel, BoxLayout.Y_AXIS));
menuPanel.add(...);
menuPanel.add(...);

JPanel center = new JPanel();
center.setLayout(...);
center.setBackground( Color.BLUE );
center.add(...);

frame.add(menuPanel, BorderLayout.LINE_START);
frame.add(center, BorderLayout.CENTER);
frame.pack();
frame.setVisible( true );

要点是按逻辑分解面板并将它们一次一个地添加到框架中。所以首先获取添加到框架中的菜单及其子组件的正确位置。然后您可以添加 CENTER 面板及其子组件。