我正在用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();
}
}
}
答案 0 :(得分:2)
只需在名为NumberPanel
的{{1}}中创建一个静态NumberPanel
字段:
current
这样的事情应该跟踪当前点击的面板。