JavaFX:截图功能
Posted xhBruce
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaFX:截图功能相关的知识,希望对你有一定的参考价值。
JavaFX:截图功能
b站up主Aimls的课程:JavaFX开发桌面截图功能
码农教程:基于Javafx的截图功能实现
脚本之家:Java模拟QQ桌面截图功能实现方法
鼠标事件
- 鼠标按下MousePressed
- 鼠标按下拖拽MouseDragged
- 鼠标释放MouseReleased
screenShortPane.setOnMousePressed(screenMouseEvent);
screenShortPane.setOnMouseDragged(screenMouseEvent);
screenShortPane.setOnMouseReleased(screenMouseEvent);
// ... ... ... ...
private EventHandler<MouseEvent> screenMouseEvent = event -> {
EventType<MouseEvent> eventType = (EventType<MouseEvent>) event.getEventType();
switch (eventType.getName()) {
case "MOUSE_PRESSED": {
// ... ... ... ...
break;
}
case "MOUSE_DRAGGED": {
// ... ... ... ...
break;
}
case "MOUSE_RELEASED": {
sceneX_end = event.getSceneX();
sceneY_end = event.getSceneY();
hbox.setPrefWidth(sceneX_end - sceneX_start);
hbox.setPrefHeight(sceneY_end - sceneY_start);
try {
getScreenImg();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
default:
break;
}
};
设置透明背景
- 缩小前一个stage:setIconified(true)
- Stage透明属性:
setFill(Paint.valueOf("#ffffff03"))、setStyle("-fx-background-color:#B5B5B522")、initStyle(StageStyle.TRANSPARENT)
- 截图全屏显示区域
setFullScreen(true)
public void loadStage() {
JxhScreenshot.screenShotStage = new Stage();
JxhScreenshot.window.setIconified(true);
FXMLLoader fxmlLoader = new FXMLLoader(PathInfo.getfxml("screenshot.fxml"));
Scene scene = null;
try {
fxmlLoader.setController(ScreenshotController.getInstance());
scene = new Scene(fxmlLoader.load());
} catch (IOException e) {
e.printStackTrace();
}
scene.setFill(Paint.valueOf("#ffffff03"));
screenShortPane.setStyle("-fx-background-color:#B5B5B522");
JxhScreenshot.screenShotStage.setFullScreenExitHint("");
JxhScreenshot.screenShotStage.setScene(scene);
JxhScreenshot.screenShotStage.setFullScreen(true);
JxhScreenshot.screenShotStage.initStyle(StageStyle.TRANSPARENT);
JxhScreenshot.screenShotStage.show();
scene.setOnKeyPressed(keyEvent -> {
if (keyEvent.getCode() == KeyCode.ESCAPE) {
JxhScreenshot.screenShotStage.close();
JxhScreenshot.window.setIconified(false);
}
});
}
截屏使用awt
import java.awt.*;
import java.awt.image.BufferedImage;
Robot robot = new Robot();
Rectangle rec = new Rectangle((int) (sceneX_start + 2), (int) (sceneY_start + 2), (int) (w - 4), (int) (h - 4));
BufferedImage buffimg = robot.createScreenCapture(rec);
BufferedImage转换
img = SwingFXUtils.toFXImage(buffimg, null);
截切板保存
Clipboard cb = Clipboard.getSystemClipboard();
ClipboardContent content = new ClipboardContent();
content.putImage(img);
cb.setContent(content);
ImageIO.write(buffimg, "png", new File("D:/img.png"));
上传到Gitee
(将IntelliJ IDEA项目传上传至Gitee上)
https://gitee.com/xhbruce/xh-desktop-screenshot
新增:代码中设置Controller
- 代码中动态设置Controller
- ScreenshotController.getInstance()单例模式通信
新增:关闭窗口弹框
新增:弹框关闭选择保存
- showSaveDialog选择文件保存,或命名文件保存
以上是关于JavaFX:截图功能的主要内容,如果未能解决你的问题,请参考以下文章