S
S
svetlov972018-05-04 00:56:13
Java
svetlov97, 2018-05-04 00:56:13

Why is the window twitching when dragging?

The problem is that the window shakes while dragging and it deviates from the cursor. Why might this be?
Here is the code:

package youpackagename;

import java.awt.Color;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Rectangle2D;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

/**
 *
 * @author keeptoo
 */
public class JavaFXMovable extends Application {

   //define your offsets here
    private double xOffset = 0;
    private double yOffset = 0;
    
    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
        //you can use underdecorated or transparent.
        stage.initStyle(StageStyle.TRANSPARENT);
        //stage.initStyle(StageStyle.UNDERDECORATED);
       
       //grab your root here
             root.setOnMousePressed(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                xOffset = event.getSceneX();
                yOffset = event.getSceneY();
            }
        });
        
        //move around here
        root.setOnMouseDragged(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                stage.setX(event.getScreenX() - xOffset);
                stage.setY(event.getScreenY() - yOffset);
            }
        });
       
        Scene scene = new Scene(root);
        stage.setScene(scene);   

        stage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
Codebaker, 2018-05-05
@svetlov97

I'll duplicate the answer from the comments.
Try this: in the first handler:

xOffset = stage.getX() - event.getScreenX();
yOffset = stage.getY() - event.getScreenY();

And in setOnMouseDragged:
stage.setX(event.getScreenX() + xOffset);
stage.setY(event.getScreenY() + yOffset);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question