18

如何在 JavaFX 2.1 中检测场景或舞台何时更改大小?我找不到任何事件处理程序。

4

3 回答 3

21

heightPropertywidthProperty。您可以使用这些属性进行绑定,或向它们添加侦听器。

public void start(Stage stage) {
    Scene scene = new Scene(new Group(), 300, 200);
    stage.setScene(scene);

    stage.titleProperty().bind(
            scene.widthProperty().asString().
            concat(" : ").
            concat(scene.heightProperty().asString()));

    stage.show();
}

或查看下一个示例:https ://stackoverflow.com/a/9893911/1054140

于 2012-05-27T13:13:39.513 回答
11

在重新调整场景大小后执行操作的一种方法是完成,您可以这样做:

(注意:可能有更好的方法来做到这一点,对我来说它完成了工作)

final Stage primaryStage = getStage() // get your stage from somewhere

// create a listener
final ChangeListener<Number> listener = new ChangeListener<Number>()
{
  final Timer timer = new Timer(); // uses a timer to call your resize method
  TimerTask task = null; // task to execute after defined delay
  final long delayTime = 200; // delay that has to pass in order to consider an operation done

  @Override
  public void changed(ObservableValue<? extends Number> observable, Number oldValue, final Number newValue)
  {
    if (task != null)
    { // there was already a task scheduled from the previous operation ...
      task.cancel(); // cancel it, we have a new size to consider
    }

    task = new TimerTask() // create new task that calls your resize operation
    {
      @Override
      public void run()
      { 
        // here you can place your resize code
        System.out.println("resize to " + primaryStage.getWidth() + " " + primaryStage.getHeight());
      }
    };
    // schedule new task
    timer.schedule(task, delayTime);
  }
};

// finally we have to register the listener
primaryStage.widthProperty().addListener(listener);
primaryStage.heightProperty().addListener(listener);
于 2014-09-12T16:33:03.363 回答
2

这太旧和基本但它可能会帮助像我这样的菜鸟

您可以将侦听器添加到宽度和高度属性

stage.heightProperty().addListener(e ->{
    handle....
});

stage.widthProperty().addListener(e ->{
    handle....
});
于 2018-02-28T17:32:08.257 回答