问题
I'm making a GUI pairs guessing game with 9x12 panels to hold a random number in each. I have made it so when you hover over each individual panel, it changes from red to yellow, and back to red once your mouse leaves the panel area. My problem now is changing the color of a clicked panel to green, and any previously clicked panel back to it's original color red. It turns green as intended, but am lost as to how to reset the previously clicked panel back to red after a new panel is clicked. I'm hoping there is an obvious answer but here is some relevant code (Not polished off):
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();
}
}
}
回答1:
Just create a static NumberPanel
field in NumberPanel
called current
:
private static NumberPanel current;
...
// create a static MouseListener instead of creating a new one for each
// NumberPanel instance.
private static final MouseAdapter mouseListener = new MouseAdapter(){
public void mousePressed(MouseEvent event) {
NumberPanel panel = (NumberPanel) event.getSource();
if(current != null) {
current.mouseClicked = false;
}
current = panel;
panel.mouseClicked = true;
// repaint number panels container
}
}
...
addMouseListener(mouseListener);
Something like that should keep track of the current clicked panel.
来源:https://stackoverflow.com/questions/17008724/mouseclicked-event-to-setbackground-of-a-panel