在JPanel上重新绘制/刷新JLabel

时间:2011-04-02 09:23:54

标签: java swing jpanel repaint paintcomponent

我无法在运行时更新2D数组中的JLabel。

我正在研究的程序是Connect Four的一个变种。我创建了一个JLabel的2D数组,它们都默认为包含空白插槽图像的ImageIcon。玩家1和2选择他们的颜色,并且在玩家的回合中,他可以点击将一个棋子放入一列(重力导致棋子掉到底部或直到它落在另一个棋子上)。

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

p1,p2和current是Player对象。 grid [] []是一个2D数组,其整数设置为0,1或2,以便更容易地跟踪谁拥有哪些图块。 tiles [] []是我的JLabel的2D数组。

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();

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

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

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

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

1 个答案:

答案 0 :(得分:3)

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

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