我正在尝试创建一个从URL获取屏幕截图的Javafx应用程序。我遇到问题的地方是线程。在我的主要方法中,我正在尝试运行两个屏幕截图,但在加载第一页后它会卡住。我试图在提交给执行者的任务(下面的代码)中包装monitorPageStatus()(因为它调用实际的saveToPng()函数)方法。如何正确地将任务提交给执行者,以便截取两个截图?
public class InsightScreenshot {
{
// Clever way to init JavaFX once
JFXPanel fxPanel = new JFXPanel();
}
private Browser browser;
public Stage stage;
private Timer timer = new java.util.Timer();
private ExecutorService exec = Executors.newSingleThreadExecutor(r -> {
Thread t = new Thread(r);
t.setDaemon(true); // allows app to exit if tasks are running
return t ;
});
@SuppressWarnings("restriction")
/**
*
* @param url
* @param imageName add png extension
*/
public void showWindow(String url, String imagePath) {
// JavaFX stuff needs to be done on JavaFX thread
Platform.runLater(new Runnable() {
private Stage window;
@SuppressWarnings("restriction")
@Override
public void run() {
Stage window = new Stage();
window.setTitle(url);
browser = new Browser(url);
monitorPageStatus(imagePath, window);
VBox layout = new VBox();
layout.getChildren().addAll(browser);
Scene scene = new Scene(layout);
window.setScene(scene);
//window.setOnCloseRequest(we -> System.exit(0));
window.show();
}
});
}
private void monitorPageStatus(String imageName, Stage window) {
timer.schedule(new TimerTask() {
@SuppressWarnings("restriction")
public void run() {
Platform.runLater(() -> {
if (browser.isPageLoaded()) {
System.out.println("Page now loaded, taking screenshot...");
saveAsPng(imageName);
window.close();
cancel();
} else
System.out.println("Loading page...");
});
}
}, 1000, 1000);
}
private void saveAsPng(String imageName) {
WritableImage image = browser.snapshot(new SnapshotParameters(), null);
//TODO change file path?
File file = new File(imageName);
try {
ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file);
System.out.println("Screenshot saved as " + imageName);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
InsightScreenshot pic = new InsightScreenshot();
pic.showWindow("ttps://www.google.com", "/images/google.png");
InsightScreenshot pic2 = new InsightScreenshot();
pic2.showWindow("https://www.facebook.com", "/images/fb.png");
}
}