Had a situation where a panel was getting dragged, and the mouse could “escape” the window if it was moved quickly enough. What was happening was the mouse cursor was leaving the panel, and no more events would arrive to complete or update the drag (since the mouse was now over a different element or background).
Figured this might help someone else if they ran across the same problem.
Setting up the subscription (eventbus)
[java]
nifty.subscribe( screen, basePanel.getId(), NiftyMouseEvent.class, windowMoveSubscriber );
[/java]
The subscriber / window dragger
[java]
private EventTopicSubscriber<NiftyMouseEvent> windowMoveSubscriber = new EventTopicSubscriber<NiftyMouseEvent>() {
private int lastMouseX, lastMouseY;
private boolean dragging = false;
@Override
public void onEvent( final String topic, final NiftyMouseEvent data ) {
int x = data.getMouseX(), y = data.getMouseY();
if ( ! App.isCtrlDown ) return; // App is tracking meta key events, globally
if ( dragging && data.isButton0Release() ) {
dragging = false;
}
else if ( ! dragging && data.isButton0InitialDown() ) {
// save the location
lastMouseX = x;
lastMouseY = y;
dragging = true;
// setup an additional handler to lock the mouse into this window
nifty.getEventService().subscribeStrongly( Pattern.compile( “." ), new EventTopicSubscriber() {
@Override
public void onEvent( String topic, Object data ) {
if ( data instanceof NiftyMousePrimaryReleaseEvent ) {
dragging = false;
nifty.getEventService().unsubscribe( Pattern.compile( ".” ), this );
}
else if ( data instanceof NiftyMouseEvent ) {
windowMoveSizeSubscriber.onEvent( “basePanel”, (NiftyMouseEvent) data ); // forward mouse onto the original subscriber
}
}
} );
}
else if ( dragging && (x != lastMouseX || y != lastMouseY) ) {
// calculate the delta
int dx = lastMouseX - x;
int dy = lastMouseY - y;
// adjust the window
// move it
Box box = basePanel.getLayoutPart().getBox();
int curX = box.getX();
int curY = box.getY();
basePanel.setConstraintX( new SizeValue( String.valueOf( curX - dx ) + “px” ) );
basePanel.setConstraintY( new SizeValue( String.valueOf( curY - dy ) + “px” ) );
basePanel.getParent().layoutElements();
lastMouseX = x;
lastMouseY = y;
}
}
};
[/java]
The additional subscribeStrongly using the wildcard and class checks is used to forward ALL mouse events to the original subscriber until a termination event (buttonUp, controlKeyUp) happened.
Happy coding…
I just wanted to add that losing a window while dragging it should not happen with Nifty 1.3.2. So the additional code / workaround that novum posted is not necessary anymore.