gpt4 book ai didi

java - 在 JPanel 上重新绘制/刷新 JLabel

转载 作者:行者123 更新时间:2023-11-29 06:14:44 26 4
gpt4 key购买 nike

我无法在运行时更新二维数组中的 JLabel。

我正在开发的程序是 Connect Four 的一个变体。我创建了一个 JLabel 的二维数组,它们都默认为包含空白槽图像的 ImageIcon。玩家 1 和 2 选择他们的颜色,轮到玩家时,他可以点击将一个棋子放到一列中(重力导致棋子掉到底部或直到它落在另一个棋子上面)。

我非常肯定我的 addToColumn 方法工作正常。我唯一的问题是我似乎无法更新任何 JLabel。这是我正在研究的方法:

p1、p2 和 current 是 Player 对象。 grid[][] 是一个二维整数数组,设置为 0、1 或 2,以便更轻松地跟踪谁拥有哪些图 block 。 tiles[][] 是我的 JLabel 二维数组。

public void addToColumn(int column) { // drop a tile in the specified column
int i = 0;
while (grid[column][5-i] != 0) i++; // move upward through the 6 rows of tiles
// until we find an empty one
if (current == p1) grid[column][5-i] = 1; // update to the current player's value
else grid[column][5-i] = 2;

tiles[column][5-i] = new JLabel(findColorIcon(current.getColor()));

tiles[column][5-i].setIcon(findColorIcon(current.getColor()));

repaint();

现在,最后两行更改了 tiles[][] 中的 JLabel,显然我不需要两者,不确定哪种方法更好……这只是我尝试过的一些方法,但无济于事。 (我的 getColor() 方法返回 Color,findColorIcon(Color c) 返回具有该图 block 颜色的相应 JLabel)。

是的,我也在我的 paintComponent 方法中添加了:

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
}

我已经坚持了一段时间,我觉得我错过了一些明显的东西。有什么建议吗?

最佳答案

我没有看到您的 paintComponent() 方法有任何作用。特别是,替换 JLabel 需要您 validate() 容器。作为替代方案,您可能想看看这个 game 是如何简单的使用 Model–View–Controller 图案并绘制彩色图标。

附录:此相关example描述了如何只替换 Icon,而不是整个 JLabel。相比之下,这个 example显示如何在替换组件后validate() 容器。

关于java - 在 JPanel 上重新绘制/刷新 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5522336/

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