Last active
July 1, 2019 23:13
-
-
Save am4dr/b3b60ff78fd4264e0b840a7a6f134cf1 to your computer and use it in GitHub Desktop.
JavaFX screen capture sample (with java.awt.Robot)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* JavaFX Screen Capture with java.awt.Robot | |
* run: groovy javafx_screen-capture_with_awt-robot.groovy | |
*/ | |
import javafx.application.Application | |
import javafx.application.Platform | |
import javafx.embed.swing.SwingFXUtils | |
import javafx.geometry.Insets | |
import javafx.scene.Parent | |
import javafx.scene.Scene | |
import javafx.scene.control.Button | |
import javafx.scene.image.ImageView | |
import javafx.scene.layout.* | |
import javafx.scene.paint.Color | |
import javafx.stage.Stage | |
import javafx.stage.StageStyle | |
import java.awt.* | |
import java.util.concurrent.CompletableFuture | |
class App extends Application { | |
void start(Stage stage) { | |
stage.initStyle(StageStyle.TRANSPARENT) | |
stage.scene = new Scene(mainPanel(), 500d, 500d, Color.TRANSPARENT) | |
stage.show() | |
} | |
Parent mainPanel() { | |
def shotButton = new Button("snapshot") | |
def capturer = new FlowPane(shotButton) | |
capturer.background = new Background(new BackgroundFill(Color.TRANSPARENT, null, null)) | |
capturer.border = new Border(new BorderStroke(Color.GREENYELLOW.with { opacity = 0.5; it }, BorderStrokeStyle.SOLID, null, new BorderWidths(1d))) | |
capturer.padding = new Insets(5d) | |
shotButton.setOnAction { | |
capturer.visible = false | |
CompletableFuture.runAsync({ | |
Thread.currentThread().sleep(60) | |
Platform.runLater { | |
snapshot(capturer) | |
capturer.visible = true | |
} | |
}) | |
} | |
return capturer | |
} | |
static void snapshot(javafx.scene.Node node) { | |
def robot = new Robot() | |
def (int x, int y) = node.localToScreen(0d, 0d).with { [x, y] } | |
def (int w, int h) = node.boundsInParent.with { [width, height] } | |
def bi = robot.createScreenCapture(new Rectangle(x, y, w, h)) | |
def writableImage = SwingFXUtils.toFXImage(bi, null) | |
new Stage().with { | |
title = 'snapshot' | |
scene = new Scene(new Pane(new ImageView(writableImage))) | |
show() | |
} | |
} | |
} | |
Application.launch(App) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment