当元素从窗格中移除时,防止 GridBagLayout 调整列/行的大小?
Prevent GridBagLayout from resizing columns / rows when elements are removed from pane?
我正在制作一个简单的游戏,用户可以在其中单击以删除按钮,但是当删除按钮时,我在调整 GridBagLayout 大小时遇到了一些问题。
默认 window 如下所示:
当一个按钮被点击时,它被移除:
但是,当删除行/列中的每个按钮时,gridbag 会调整大小并且按钮会变大:
有什么方法可以防止这种行为发生? IE。向 gridbag 添加填充以保持所有列/行的分布,因为它们最初在未填充区域有空白?
此外,这是我的一些代码:
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();
}
}
Is there a way I can prevent this behavior from happening?
您可以使用 GridLayout
。然后你可以使用:
button.setVisible( false );
并且space将保留在网格中。
否则,您需要通过向网格添加虚拟组件来保留网格中的 space(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 教程部分了解更多信息。
我正在制作一个简单的游戏,用户可以在其中单击以删除按钮,但是当删除按钮时,我在调整 GridBagLayout 大小时遇到了一些问题。
默认 window 如下所示:
当一个按钮被点击时,它被移除:
但是,当删除行/列中的每个按钮时,gridbag 会调整大小并且按钮会变大:
有什么方法可以防止这种行为发生? IE。向 gridbag 添加填充以保持所有列/行的分布,因为它们最初在未填充区域有空白?
此外,这是我的一些代码:
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();
}
}
Is there a way I can prevent this behavior from happening?
您可以使用 GridLayout
。然后你可以使用:
button.setVisible( false );
并且space将保留在网格中。
否则,您需要通过向网格添加虚拟组件来保留网格中的 space(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 教程部分了解更多信息。