如何在JavaFX中侦听resize事件

时间:2012-05-27 09:39:22

标签: javafx-2

如何在JavaFX 2.1中检测场景或舞台何时改变大小?我找不到任何EventHandler。

3 个答案:

答案 0 :(得分:20)

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

答案 1 :(得分:9)

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

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

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);

答案 2 :(得分:0)

这太古老而且基本但它可能对像我这样的菜鸟有帮助

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

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

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