首页 > 解决方案 > GridBagLayout Swing 中的 JSpinners 和 JButton

问题描述

这是我创建消息面板的代码:

private class MessagePane extends JPanel {
    private MessagePane() {
        setLayout(new GridBagLayout());
        setBackground(backgroundColor);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.insets = new Insets(4, 4, 4, 4);

        add(allowButton, gbc);
        gbc.gridx = 1;
        add(blockButton, gbc);

        gbc.gridwidth = 2;
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 1;
        gbc.weighty = 1;
        add(timerL, gbc);
        gbc.fill = GridBagConstraints.BOTH;
        add(new JScrollPane(messageArea), gbc);

        gbc = new GridBagConstraints();
        gbc.gridy = 2;
        gbc.gridx = 0;
        add(countryList, gbc);

        gbc.gridx = 1;
        add(msgList, gbc);

        gbc.gridx = 2;
        add(sendButton, gbc);

        setVisible(true);
    }
}

这看起来像:

外观不好的面板

我想要实现的观点:

好看的面板

你能帮我解决这个问题吗?

标签: javaswingjbuttonlayout-managerjspinner

解决方案


您没有正确设置 gbc 约束宽度,但话虽如此,对于这个 GUI,我不会使用 GridBagLayout。我会:

  • 对整个 JPanel 使用 BorderLayout
  • 使用 GridLayout 将顶部按钮添加到 JPanel,其中 1 行 2 列,中间有一些空间
  • 将该 JPanel 放入主 JPanelBorderLayout.PAGE_START
  • 放置中心组件BorderLayout.CENTER
  • 使用沿线(而不是页面)定向的 BoxLayout 为底部创建一个 JPanel
  • 将其添加到主 JPanelBorderLayout.PAGE_END

推荐阅读