我正在制作一个带有 9x12 面板的 GUI 配对猜谜游戏,以在每个面板中保存一个随机数。我已经做到了,所以当您将鼠标悬停在每个单独的面板上时,它会从红色变为黄色,一旦您的鼠标离开面板区域,它就会变回红色。我现在的问题是将单击的面板的颜色更改为绿色,并且将任何以前单击的面板变回原来的红色。它按预期变为绿色,但在单击新面板后如何将先前单击的面板重置为红色时迷失了方向。我希望有一个明显的答案,但这里有一些相关的代码(未抛光):
public class NumberPanel extends JPanel {
int rand;
Random generator = new Random();
JLabel numbers;
boolean mouseEntered = false;
boolean mouseClicked = false;
boolean mouseUnClicked = false;
MainPanel mp;
public NumberPanel() {
setBackground(Color.RED);
setPreferredSize (new Dimension(40,40));
rand = generator.nextInt(8) +1;
addMouseListener(new NumberListener());
}
public NumberPanel (MainPanel mp) {
//Callback method for MainPanel
this.mp = mp;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Font font = new Font("Verdana", Font.BOLD, 18);
g.setFont(font);
g.drawString("" +rand, 14,24);
if (mouseEntered) {
setBackground(Color.YELLOW);
}
else {
setBackground(Color.RED);
}
if (mouseClicked) {
setBackground(Color.GREEN);
}
}
//represents the listener for mouse events
private class NumberListener implements MouseListener {
public void mouseEntered (MouseEvent event) {
mouseEntered=true;
repaint();
}
public void mouseExited(MouseEvent event) {
mouseEntered=false;
repaint();
}
public void mouseClicked(MouseEvent event) {
}
public void mouseReleased(MouseEvent event) {
}
public void mousePressed(MouseEvent event) {
mouseClicked=true;
repaint();
}
}
}