Entry
Is it possible to prevent the mouse from exiting a window and how ?
Oct 27th, 2004 23:03
Tom McGuire, Vane Trajkov,
You could try this nasty bit of coding, however my gut tells me that
99% of the time, what you are trying to do is bad design.
public class TrapPanel extends JPanel{
private Point lastMousePosition;
private Robot robot;
public TrapPanel(){
super(null);
try{
robot = new Robot();
}catch(AWTException awt){
System.err.println("Robot not available");
}
addMouseListener(new MouseAdapter() {
public void mouseExited(MouseEvent e) {
if(robot!=null){
Point p = getLocation();
p.translate(lastMousePosition.x,lastMousePosition.y);
SwingUtilities.convertPointToScreen(p,e.getComponent());
robot.mouseMove(p.x,p.y);
}
}
});
addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
lastMousePosition = e.getPoint();
}
public void mouseMoved(MouseEvent e) {
lastMousePosition = e.getPoint();
}
});
}
}