gpt4 book ai didi

java - mouseEntered 不会执行

转载 作者:行者123 更新时间:2023-12-01 18:52:15 26 4
gpt4 key购买 nike

我正在尝试进行 mouseEntered 测试来更改方形颜色,但是 MouseListener mouseEntered 不会执行。鼠标有响应,但仅对单击、按下和释放有响应。所以我不确定发生了什么事。希望您能帮我指出我的问题,谢谢。

//Class
class RectangleClass extends JPanel{
private int height;
private int width;
private boolean MouseEntered= false;
private boolean MouseExit= false;
private JPanel myPanel = new JPanel();
//Inner class with mouse Event
class RectangleAdapter extends MouseAdapter{

public void MouseEntered(MouseEvent e){
System.out.println("MouseEntered");
MouseEntered = true;
repaint();
}

public void MouseExited(MouseEvent e){
System.out.println("MouseExited");
MouseExit = true;
repaint();
}

}
//constructor
public RectangleClass(int height,int width){

myPanel = this;
this.height=height;
this.width=width;
this.addMouseListener(new RectangleAdapter());
}
//paint graphic
public void paint(Graphics g){
super.paint(g);
g.clearRect(0, 0, width, height);
g.drawRect(0, 0, width, height);
g.setColor(Color.YELLOW);

if (MouseEntered){
g.setColor(Color.CYAN);
MouseEntered= false;
}
if (MouseExit){
g.setColor(Color.orange);
MouseExit= false;
}
g.fillRect(0, 0, width, height);
}
}

public class RectangleContainer extends JFrame{

public RectangleContainer(){
setLayout(null);
JPanel myPanel = new RectangleClass(100,100);
myPanel.setBounds(50, 50, 200, 200);
setSize(200,200);
add(myPanel);
setVisible(true);
}

public static void main(String args[]){
new RectangleContainer();
}
}

最佳答案

您实际上并没有覆盖 mouseEntered MouseAdapter的方法,你需要

@Override
public void mouseEntered(MouseEvent e) {

添加@Override将使编译器检查您是否覆盖了正确的方法。这同样适用于 mouseExited顺便说一句。

<小时/>

附注:

  • 不要使用null layout - 始终使用layout manager
  • 对于自定义绘画,覆盖 paintComponent 而不是 paint
  • Java 命名约定表明所有变量均以小写 字母开头,这将使变量 MouseEntered mouseEntered

关于java - mouseEntered 不会执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15457160/

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