gpt4 book ai didi

java - 用于设置面板背景的 MouseClicked 事件

转载 作者:行者123 更新时间:2023-12-02 06:58:22 28 4
gpt4 key购买 nike

我正在制作一个 GUI 配对猜谜游戏,带有 9x12 面板,每个面板中保存一个随机数。我已经做到了,当您将鼠标悬停在每个单独的面板上时,它会从红色变为黄色,并在鼠标离开面板区域后变回红色。我现在的问题是将单击的面板的颜色更改为绿色,并将任何先前单击的面板更改回其原始颜色红色。它按预期变成绿色,但我不知道如何在单击新面板后将先前单击的面板重置回红色。我希望有一个明显的答案,但这里有一些相关代码(未完善):

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

最佳答案

只需在 NumberPanel 中创建一个名为 current 的静态 NumberPanel 字段即可:

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

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

关于java - 用于设置面板背景的 MouseClicked 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17008724/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com