Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

java - JavaFX class controller scene reference

Is there any way of getting the Scene object of an FXML loaded file from the associated class controller.

I'm doing something like this:

@FXML
private AnchorPane anchor; 

Scene scene = anchor.getScene();

but i'd like a solution that does not reference the AnchorPane control.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why not? Controller is an abstract class, he's not aware about UI unless you deliberately make him know.

Nodes (inlcuding AnchorPane) are another story, they hardly exists outside for scenegraph. So it's perfectly fine to ask Node about his parent or scene.

If you still want to handle that separately there are next approaches:

  1. you can create a custom controller and set scene after loader. Just note that at the time initialize() called it wouldn't yet initialized.

    public class MyController {
        private void Scene scene;
        public void setScene(Scene scene) { this.scene = scene; }
    
    }
    
    // loading code
    FXMLLoader fxmlLoader = new FXMLLoader();
    AnchorPane root = (AnchorPane) fxmlLoader.load(getClass().getResource("MyApp.fxml"));
    MyController myController = (MyController) fxmlLoader.getController();
    myController.setScene(scene);
    
  2. You can create a custom fxml control which will incorporate controller and he can just call getScene() for itself. See an example here: https://stackoverflow.com/a/10718683/1054140


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...