I have a program that displays a 4x4 grid of squares through a GridBagLayout layout manager. 16 JLabels which all contain a square.gif are displayed. When one of the rectangles is clicked, it is supposed to be replaced with a JLabel that contains an image (e.g, such as a hat). So, the image takes the place of the rectangle that is clicked on.
However, what happens at the moment is that the rectangle that is clicked only gets replaced sometimes. Other times, the rectangle disappears but the image does not replace it. Other times, the image displays in a rectangle that has been clicked previously but only after clicking a different rectangle. I have placed the most relevant code below.
public void displayGrid() {
c.gridx = 0;
c.gridy = 0;
try {
squareImage = ImageIO.read(this.getClass().getResource("stimulus(0).gif")); //line 37
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JLabel squareLabel = new JLabel(new ImageIcon(squareImage));
for(int i = 0; i < 16; i++){
c.gridx = i % 4;
c.gridy = i / 4;
squareLabel = new JLabel(new ImageIcon(squareImage));
squareLabels[i] = squareLabel;
panel.add(squareLabels[i], c);
squareLabels[i].addMouseListener(this);
System.out.println(c.gridx + "" + c.gridy);
}
panel.validate();
}
public void mousePressed(MouseEvent e) {
for(int i = 0; i < squareLabels.length; i++){
if(e.getSource() == squareLabels[i]){
//JLabel removedLabel = squareLabels[i];
c.gridx = (i/4);
c.gridy = (i%4);
panel.remove(squareLabels[i]);
panel.revalidate();
panel.repaint();
panel.add(stimuliLabels[0], c);
panel.validate();
}
}
}
In the mousePressed() method, I have attempted to write code that determines the JLabel that is pressed, gets the GridBagConstraints of that JLabel, removes the JLabel that is clicked on, and then replaces that JLabel with the new JLabel with the given GridBagConstraints. However, as I have already said, the program is not working as planned, and I don't know why.
Thank you for taking the time to read this. Any help would be appreciated.