Reputation: 103
I'm building a javafx application where one of the scenes involves colored circles and lines. Depending upon certain condition I need to change the colors. I wanted to save the resulting updated scene as an image for later use. While taking a screenshot is an option, under some conditions only the calculated data is stored in database and the updated scene is not shown on screen.
So is it possible to somehow get a resulting image from an fxml without displaying on screen?
Upvotes: 2
Views: 927
Reputation: 209583
Yes: you can do
Image fxmlImage = new Scene(FXMLLoader.load(getClass().getResource("/path/to/fxml")))
.snapshot(null);
Note that the controller class, if specified in the FXML, must be on the classpath for this to work.
Here's a SSCCE (bear in mind the above caveat when running):
import java.io.File;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Stage;
public class FXMLViewer extends Application {
@Override
public void start(Stage primaryStage) {
Button loadButton = new Button("Load");
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().add(new ExtensionFilter("FXML files", "*.fxml"));
loadButton.setOnAction(e -> {
File file = fileChooser.showOpenDialog(primaryStage);
if (file != null) {
try {
Image image = new Scene(FXMLLoader.load(file.toURI().toURL())).snapshot(null);
showImage(image, primaryStage);
} catch (Exception exc) {
exc.printStackTrace();
}
}
});
StackPane root = new StackPane(loadButton);
Scene scene = new Scene(root, 350, 120);
primaryStage.setScene(scene);
primaryStage.show();
}
private void showImage(Image image, Stage owner) {
double width = Math.max(400, image.getWidth());
double height = Math.max(400, image.getHeight());
ScrollPane root = new ScrollPane(new ImageView(image));
Scene scene = new Scene(root, width, height);
Stage stage = new Stage();
stage.initOwner(owner);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Upvotes: 4