How to convert node to image in javafx 2.1?

后端 未结 3 616
感情败类
感情败类 2020-12-03 17:59

I am using Java FX and I would like to convert a node to an image. I found this resource, but it does not solve my problem as I want to convert a node to an image, not a who

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 18:29

    You can use new FX 2.2 snapshot feature:

    public class TrySnapshot extends Application {
    
        @Override
        public void start(Stage primaryStage) {
            final VBox vbox = new VBox(2);
            final Button btn = new Button();
            vbox.getChildren().add(btn);
            btn.setText("Say 'Hello World'");
            btn.setOnAction(new EventHandler() {
                @Override
                public void handle(ActionEvent event) {
                    // here we make image from vbox and add it to scene, can be repeated :)
                    WritableImage snapshot = vbox.snapshot(new SnapshotParameters(), null);
    
                    vbox.getChildren().add(new ImageView(snapshot));
                    System.out.println(vbox.getChildren().size());
                }
            });
    
            Scene scene = new Scene(new Group(vbox), 300, 250);
    
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    

    If you must use older FX for some reason just change scene coordinates to your node coordinates using Node#getBoundsInParent calls in the code sample you linked.

提交回复
热议问题