JavaFX example to capture screen/GUI nodes:
package javafxcapturescreen; import java.io.File; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Application; import javafx.embed.swing.SwingFXUtils; import javafx.event.ActionEvent; import javafx.scene.Scene; import javafx.scene.SnapshotParameters; import javafx.scene.control.Button; import javafx.scene.image.WritableImage; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javax.imageio.ImageIO; /** * * @web http://java-buddy.blogspot.com/ */ public class JavaFXCaptureScreen extends Application { @Override public void start(Stage primaryStage) { StackPane root = new StackPane(); Scene scene = new Scene(root, 300, 250); Button btnCaptureScene = new Button(); btnCaptureScene.setText("Capture scene"); btnCaptureScene.setOnAction((ActionEvent event) -> { WritableImage writableImage = scene.snapshot(null); File file = new File("capturedScene.png"); try { ImageIO.write(SwingFXUtils.fromFXImage(writableImage, null), "png", file); System.out.println("Captured: " + file.getAbsolutePath()); } catch (IOException ex) { Logger.getLogger(JavaFXCaptureScreen.class.getName()).log(Level.SEVERE, null, ex); } }); Button btnCaptureRoot = new Button(); btnCaptureRoot.setText("Capture root"); btnCaptureRoot.setOnAction((ActionEvent event) -> { WritableImage writableImage = root.snapshot(new SnapshotParameters(), null); File file = new File("capturedRoot.png"); try { ImageIO.write(SwingFXUtils.fromFXImage(writableImage, null), "png", file); System.out.println("Captured: " + file.getAbsolutePath()); } catch (IOException ex) { Logger.getLogger(JavaFXCaptureScreen.class.getName()).log(Level.SEVERE, null, ex); } }); VBox vBox = new VBox(); vBox.getChildren().addAll(btnCaptureScene, btnCaptureRoot); root.getChildren().add(vBox); primaryStage.setTitle("java-buddy.blogspot.com"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
capturedScene.png |
capturedRoot.png |
No comments:
Post a Comment