gpt4 book ai didi

Java GridBayLayout 替换组件

转载 作者:行者123 更新时间:2023-12-02 04:46:28 24 4
gpt4 key购买 nike

我正在尝试使用 GridBagLayout 删除 JPanel 中的多个组件

javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
createAndShowGUI();

GamePanel gamePanel = new GamePanel(frame.getContentPane());
gamePanel.delBlock(0, 0);
gamePanel.delBlock(0, 1);

frame.setContentPane(gamePanel);

}
});

这是删除 block 的方法

public void delBlock(int x, int y){

int location = x * row + y;
this.remove(location);

this.revalidate();
this.repaint();

}

如您所见,这两个 block 应该彼此相邻,但这就是我得到的结果。

enter image description here

最佳答案

    gamePanel.delBlock(0, 0);
gamePanel.delBlock(0, 1);

首先删除位置 0 处的组件。然后所有组件在容器中移动 1 个位置。

然后您删除位置 1 处的组件。但是,在您删除第一个组件之前,该组件位于位置 2 处。

尝试:

    gamePanel.delBlock(0, 1);
gamePanel.delBlock(0, 0);

颠倒删除组件的顺序。

这总是首先从容器末端删除组件。

As you can see the 2 blocks should be next to one another

我不知道你的意思是垂直意义上的“旁边”还是水平意义上的“旁边”。

鉴于这两个组件已从第一列中删除,看来您正在按列顺序构建网格。也就是说,您添加第 1 列的所有组件,然后是第 2 列,然后是第 3 列,依此类推。

如果您希望组件彼此“相邻”(在水平意义上),那么您需要按行顺序添加组件。

关于Java GridBayLayout 替换组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29618052/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com