Repainting/refreshing JLabels on a JPanel

梦想的初衷 提交于 2019-12-11 07:01:17

问题


I'm having trouble getting my JLabels in a 2D array to update during runtime.

The program I'm working on is a variant of Connect Four. I create a 2D array of JLabels, which all default to an ImageIcon containing an image of a blank slot. Players 1 and 2 choose their colors, and on a player's turn, he can click to drop a piece into a column (gravity causes the piece to fall to the bottom or until it lands atop another piece).

I'm pretty positive that my addToColumn method is working fine. My only problem is that I can't seem to get any of the JLabels to update. Here's the method I'm working on:

p1, p2, and current are Player objects. grid[][] is a 2D array of integers set to 0, 1, or 2 to more easily track who owns which tiles. tiles[][] is my 2D array of JLabels.

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

now with those last two lines changing the JLabel in tiles[][], obviously I don't need both, not sure which way is better... that's just some of what I've tried, to no avail. (my getColor() method returns a Color, and findColorIcon(Color c) returns the corresponding JLabel with that color of tile).

and yes, I have added in my paintComponent method too:

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

I've been stuck on this for a while now, and I feel like I'm missing something obvious. any suggestions?


回答1:


I don't see that your paintComponent() method does anything. In particular, replacing a JLabel requires that you validate() the container. As an alternative, you might like to see how this simple game uses the Model–View–Controller pattern and draws colored icons.

Addendum: This related example describes how to replace just the Icon, rather than the entire JLabel. In contrast, this example shows how to validate() a container after replacing components.



来源:https://stackoverflow.com/questions/5522336/repainting-refreshing-jlabels-on-a-jpanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!