How to listen for resize events in JavaFX

2019-01-17 15:50发布

How can I detect when a Scene or Stage changes size in JavaFX 2.1? I cannot find any EventHandler for this.

标签: javafx-2
3条回答
我命由我不由天
2楼-- · 2019-01-17 16:36

There are heightProperty and widthProperty. You can use these properties for binding, or add listeners to them.

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

Or see next example: https://stackoverflow.com/a/9893911/1054140

查看更多
Melony?
3楼-- · 2019-01-17 16:52

this is too old and basic but it might help a noob like me

you can add a listener to width and height properties

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

stage.widthProperty().addListener(e ->{
    handle....
});
查看更多
太酷不给撩
4楼-- · 2019-01-17 16:57

A way to perform an action after re-sizing a scene was finished you can do this:

(Note: there maybe better ways to do this, for me it did the job)

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);
查看更多
登录 后发表回答