Moving an undecorated stage in javafx 2

前端 未结 5 637
谎友^
谎友^ 2020-12-01 05:45

I\'ve been trying to move an undecorated stage around the screen, by using the following mouse listeners:

  • onPressed
  • onReleased
  • onDragged
5条回答
  •  我在风中等你
    2020-12-01 05:59

    My guess is that your:

    onRectangleReleased()
    

    is passing the very same coordinates from your

    onRectanglePressed()
    

    This happens because as stated in the documentation the getX() method from the MouseEvent class returns

    Horizontal position of the event relative to the origin of the MouseEvent's source.

    then, when you release your mouse it actually puts your rectangle in the place it was when you first mouse pressed.

    BTW, I use a StackPane with a Rectangle inside and then apply the following code:

    private void addDragListeners(final Node n){
           n.setOnMousePressed(new EventHandler() {
                @Override
                public void handle(MouseEvent me) {
                    if(me.getButton()!=MouseButton.MIDDLE)
                    {
                        initialX = me.getSceneX();
                        initialY = me.getSceneY();
                    }
                    else
                    {
                        n.getScene().getWindow().centerOnScreen();
                        initialX = n.getScene().getWindow().getX();
                        initialY = n.getScene().getWindow().getY();
                    }
    
                }
           });
    
           n.setOnMouseDragged(new EventHandler() {
                @Override
                public void handle(MouseEvent me) {
                    if(me.getButton()!=MouseButton.MIDDLE)
                    {
                        n.getScene().getWindow().setX( me.getScreenX() - initialX );
                        n.getScene().getWindow().setY( me.getScreenY() - initialY);
                    }
                }
            });
    }
    
    addDragListeners(mainStackPane);
    

    Besides that, I use the Middle Mouse Button to center my Window on the screen. I hoped it helped. Cheers!

提交回复
热议问题