0

我正在制作一个带有 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();
        }            
    }        
}
4

1 回答 1

2

只需在调用中创建一个静态NumberPanel字段:NumberPanelcurrent

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);

类似的东西应该跟踪当前点击的面板。

于 2013-06-09T10:45:41.270 回答