GridBagLayout button.setVisible (true/false)

GridBagLayout button.setVisible (true/false)

尝试使用 GridBagLayout 构建一个非常简单的 UI,但是当在 Easy/Medium/Hard 按钮上使用 setVisible(false/true) 时,正如预期的那样,整个事情爆炸了。如何将文本字段设置在检查按钮的顶部?我确实阅读了文档,但很难掌握所有 GridBagLayout 变量背后的逻辑。

左图:正常状态
右图:当其中一个按钮(easy/medium/hard)被点击时

代码:

GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    setLayout(gridbag);

    c.weightx = 4;
    c.weighty = 4;
    c.anchor = GridBagConstraints.PAGE_END;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0; 
    c.gridy = 6;
    JButton check = buttonFactory("Check", gridbag, c);
    c.gridx = 1; 
    c.gridy = 6;
    JButton easy = buttonFactory("Easy", gridbag, c);
    c.gridx = 2; 
    c.gridy = 6;
    JButton medium = buttonFactory("Medium", gridbag, c);
    c.gridx = 3; 
    c.gridy = 6;
    JButton hard = buttonFactory("Hard", gridbag, c);

    c.gridx = 2;
    c.gridy = 4;
    c.anchor = GridBagConstraints.CENTER;
    JLabel question = labelFactory(gridbag, c);

    c.anchor = GridBagConstraints.CENTER;
    c.ipady = 30;
    c.gridwidth = 4;
    c.gridx = 0;
    c.gridy = 5;
    JSeparator separator = new JSeparator(SwingConstants.HORIZONTAL);
    gridbag.setConstraints(separator, c);
    add(separator);

    c.gridx = 2;
    c.gridy = 5;
    c.anchor = GridBagConstraints.PAGE_END;
    JLabel answer = labelFactory(gridbag, c);

    c.gridwidth = 1;
    c.gridx = 2;
    c.gridy = 6;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.anchor = GridBagConstraints.CENTER;
    JTextField userInput = new JTextField();
    gridbag.setConstraints(userInput, c);
    add(userInput); 

我不太确定我理解你的布局。看起来您正在尝试用一个按钮替换 3 个按钮。如果是这样,则使用不同的布局。

Card Layout 旨在允许您交换包含不同组件的面板。阅读 How to Use Card Layout 上的 Swing 教程部分了解更多信息。

本教程还有一个关于 How to Use GridBag Layout 的部分,它将更详细地解释约束。