【问题标题】:Prevent GridBagLayout from resizing columns / rows when elements are removed from pane?从窗格中删除元素时,防止 GridBagLayout 调整列/行的大小?
【发布时间】:2015-10-08 15:19:41
【问题描述】:

我正在制作一个简单的游戏,用户单击以删除按钮,但在删除按钮时我的 GridBagLayout 调整大小时遇到​​了一些问题。

默认窗口如下所示:

当一个按钮被点击时,它被移除:

但是,当删除行/列中的每个按钮时,gridbag 会调整大小并且按钮会变大:

有什么方法可以防止这种行为发生吗? IE。向网格包添加填充以使所有列/行保持原样分布,在未填充区域中使用空格?

另外,这是我的一些代码:

public void actionPerformed(ActionEvent e)
{
    // if we're not selecting multiple buttons and we're not clicking
    // the "select multiple" checkbox
    if ( !multiSelectState && e.getActionCommand() != "Select Multiple" )
    {
        JButton button = (JButton)e.getSource();
        p.remove(button);
        p.revalidate();
        p.repaint();
    }
}

【问题讨论】:

    标签: java swing user-interface gridbaglayout


    【解决方案1】:

    有什么方法可以防止这种行为发生吗?

    您可以使用GridLayout。然后你可以使用:

    button.setVisible( false );
    

    并且该空间将保留在网格中。

    否则,您需要通过向网格添加虚拟组件来保留网格中的空间(GridBagLayout 不包括布局中的不可见组件)。

    一种选择是将按钮替换为空面板,因此代码可能类似于:

    JPanel panel = new JPanel();
    panel.setPreferredSize( button.getPreferredSize() );
    GridBagLayout layout = (GridBagLayout)p.getLayout();
    GridBagConstraints gbc = layout.getConstraints( button );
    p.remove(button);
    p.add(panel, gbc);
    p.revalidate();
    p.repaint();
    

    另一种方法是使用带有 CardLayout 的面板。然后这个面板将包含您的 JButton 和一个空的 JPanel。

    然后,您无需从布局中删除 JButton,只需交换按钮并显示空面板。阅读 How to Use CardLayout 上的 Swing 教程部分了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-08
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      • 2012-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多