2

我有一个正在编写的程序,我需要能够检测鼠标何时离开窗口/画布。但是,据我所知,处理与 mouseOut 事件没有任何相似之处。有没有办法使用回调或事件或类似的东西来实现这一点?

4

2 回答 2

3

使用窗口位置及其边界的知识,您还可以计算指针是否在框架内。那么你可以调用你的函数。

import java.awt.Point;
import java.awt.MouseInfo;

java.awt.Insets insets;
Point mouse, win;

void setup() {
  size(400, 400);
  frame.pack();
  smooth();
}

void draw() {
  setFrame();
  if(insideFrame()) {
    background(95);
  } 
  else {
   background(0); 
  }  
}

//set position of frame
void setFrame() 
{  
  mouse = MouseInfo.getPointerInfo().getLocation();
  win = frame.getLocation();

  if(!frame.isUndecorated()){
    //add borders of window
    insets = frame.getInsets();
    win.x += insets.left;
    win.y += insets.top;
  }
}

boolean insideFrame() {
  boolean in = false;
  if(mouse.x-win.x >= 0 && width >= mouse.x-win.x)
    if(mouse.y-win.y >= 0 && height >= mouse.y-win.y)
      in = true;

  return in;
}
于 2013-10-23T11:22:50.773 回答
2

看看Java的MouseAdapter类。示例代码:

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

void setup(){
  frame.addMouseListener(new MouseAdapter(){
    public void mouseEntered(MouseEvent e){
      print("notify");
    }
  });
}
void draw(){}
于 2013-10-23T09:21:22.140 回答