Reprofiling / updating JLabels on JPanel

I am having problems updating JLabels in a 2D array at runtime.

The program I'm working on is a Connect Four option. I am creating a JLabels 2D array that defaults to ImageIcon containing an image of an empty slot. Players 1 and 2 choose their colors, and at the turn of the player, he can click to drop a piece into the column (gravity causes the piece to fall to the bottom or until it lands on top of the other part).

I am very sure that my addToColumn method works fine. My only problem is that I cannot get JLabels to update. Here is 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 these fragments. Tiles [] [] is my 2D JLabels array.

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 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 that change JLabel in the [] [] tile, obviously I don’t need both, not sure which way is better ... that only some of what I tried are inconclusive. (my getColor () method returns the color, and findColorIcon (color c) returns the corresponding JLabel with this fragment color).

and yes, I added paintComponent to my method:

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

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

+1
source share
1 answer

I do not see your paintComponent() method doing anything. In particular, replacing a JLabel requires a validate() container. Alternatively, you might like how this simple game uses Model-View-Controller and draws colored icons.

Appendix: This related example describes how to replace only Icon , not the entire JLabel . In contrast, this example shows how to validate() container after replacing components.

+3
source

Source: https://habr.com/ru/post/1433094/


All Articles