【问题标题】:Is there a way to know when the stage is moved in Java FX?有没有办法知道舞台何时在 Java FX 中移动?
【发布时间】:2016-02-23 14:31:01
【问题描述】:

在我的应用程序中,我需要在它存在的最后一个位置打开一个阶段。

目前我已经像这样实现了位置的保存:

stage.setOnHidden(event -> {
        PositionDTO dto = new PositionDTO();
        dto.setHeight(stage.getHeight());
        dto.setWidth(stage.getWidth());
        dto.setX(stage.getX());
        dto.setY(stage.getY());
        //save the position to either a file or database...
    });

但是,我想知道是否有办法在用户将窗口(舞台)拖动到新位置时设置该值,因为他们可以一次打开多个此舞台,并且在同一个位置打开是用户想要什么。他们可能没有关闭第一个打开的?

我似乎找不到可以监听的事件。

谢谢!

【问题讨论】:

  • 注册听众xProperty()yProperty()?
  • 将详细信息存储到文件或数据库是否真的会因为在移动时重复调用该事件而不堪重负?我希望能在它停止移动时发出通知。除非有办法知道它何时停止?

标签: javafx-8


【解决方案1】:

这是一种检测舞台是否停止移动的选项,以便您记录其 X 和 Y 位置的位置:

double thisX = 0;
double thisY = 0;

private boolean windowStoppedMoving() {
    boolean windowStoppedMoving = false;
    try {
        double x = thisX;
        double y = thisY;
        TimeUnit.SECONDS.sleep(2);
        boolean xNotChanged = x == thisX;
        boolean yNotChanged = y == thisY;
        windowStoppedMoving = yNotChanged && xNotChanged;
    }
    catch (InterruptedException e) {e.printStackTrace();}
    return windowStoppedMoving;
}

然后在场景窗口 xProperty 和 yProperty 上注册一个 ChangeListener:

scene.getWindow().xProperty().addListener((observable, oldValue, newValue) -> {
    thisX = (double) newValue;
    new Thread(() -> {
        if (windowStoppedMoving()) {
            double finalXValue = thisX;
            double finalYValue = thisY;
        }
    }).start();
});

scene.getWindow().yProperty().addListener((observable, oldValue, newValue) -> {
    thisY = (double) newValue;
});

当用户在屏幕上拖动窗口时,xProperty ChangeListener 在每次调用时将 thisX 设置为 newValue,然后触发线程,而 yProperty 只是在每次调用时设置 thisY 的值.线程首先记录 thisX 和 thisY 的值,然后等待 2 秒,如果这些值没有改变,则返回 true。

效果很好,只在窗口停止移动后返回一个真结果。

【讨论】:

    猜你喜欢
    • 2022-07-08
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    相关资源
    最近更新 更多