JavaFX文档指出,当达到
这表明在WebView中有一个事件,使其准备好进行捕捉,但是它是什么?
GitHub上有超过7,000个代码片段使用了
我已经尝试过:
Worker.State.SUCCEEDED
状态时,WebView
已准备就绪,但是,除非您等待一段时间(即Animation
、Transition
、PauseTransition
等),否则会呈现空白页面。这表明在WebView中有一个事件,使其准备好进行捕捉,但是它是什么?
GitHub上有超过7,000个代码片段使用了
SwingFXUtils.fromFXImage
,但它们中的大多数似乎与WebView
无关,是交互式的(人为地遮盖了竞态条件)或使用任意转换(从100毫秒到2,000毫秒不等)。我已经尝试过:
在
WebView
的尺寸(高度和宽度属性DoubleProperty
实现了ObservableValue
,可以监控这些内容)内侦听changed(...)
。- 不可行。有时,该值似乎与绘制例程分开更改,导致部分内容。
盲目地告诉任何事物都要在FX应用程序线程上
runLater(...)
。- 许多技术使用此方法,但我的单元测试(以及其他开发人员的反馈)表明事件通常已经在正确的线程上,这个调用是冗余的。我能想到的最好的方法是通过排队添加足够的延迟时间,这对一些情况有效。
向
WebView
添加DOM侦听器/触发器或JavaScript侦听器/触发器- 尽管捕获为空,但在调用
SUCCEEDED
时,JavaScript和DOM似乎都已加载。DOM / JavaScript侦听器似乎没有帮助。
- 尽管捕获为空,但在调用
使用
Animation
或Transition
来有效地“休眠”,而不会阻塞主FX线程。- ⚠️这种方法有效,如果延迟足够长,可以产生高达100%的单元测试结果,但转换时间似乎是我们只是猜测的某个未来时刻和不良设计。对于性能或任务关键型应用程序,这迫使程序员在速度或可靠性之间做出权衡,这两种情况都可能对用户产生不良体验。
什么时候调用WebView.snapshot(...)
比较合适?
用法:
SnapshotRaceCondition.initialize();
BufferedImage bufferedImage = SnapshotRaceCondition.capture("<html style='background-color: red;'><h1>TEST</h1></html>");
/**
* Notes:
* - The color is to observe the otherwise non-obvious cropping that occurs
* with some techniques, such as `setPrefWidth`, `autosize`, etc.
* - Call this function in a loop and then display/write `BufferedImage` to
* to see strange behavior on subsequent calls.
* - Recommended, modify `<h1>TEST</h1` with a counter to see content from
* previous captures render much later.
*/
代码片段:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.image.WritableImage;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Logger;
public class SnapshotRaceCondition extends Application {
private static final Logger log = Logger.getLogger(SnapshotRaceCondition.class.getName());
// self reference
private static SnapshotRaceCondition instance = null;
// concurrent-safe containers for flags/exceptions/image data
private static AtomicBoolean started = new AtomicBoolean(false);
private static AtomicBoolean finished = new AtomicBoolean(true);
private static AtomicReference<Throwable> thrown = new AtomicReference<>(null);
private static AtomicReference<BufferedImage> capture = new AtomicReference<>(null);
// main javafx objects
private static WebView webView = null;
private static Stage stage = null;
// frequency for checking fx is started
private static final int STARTUP_TIMEOUT= 10; // seconds
private static final int STARTUP_SLEEP_INTERVAL = 250; // millis
// frequency for checking capture has occured
private static final int CAPTURE_SLEEP_INTERVAL = 10; // millis
/** Called by JavaFX thread */
public SnapshotRaceCondition() {
instance = this;
}
/** Starts JavaFX thread if not already running */
public static synchronized void initialize() throws IOException {
if (instance == null) {
new Thread(() -> Application.launch(SnapshotRaceCondition.class)).start();
}
for(int i = 0; i < (STARTUP_TIMEOUT * 1000); i += STARTUP_SLEEP_INTERVAL) {
if (started.get()) { break; }
log.fine("Waiting for JavaFX...");
try { Thread.sleep(STARTUP_SLEEP_INTERVAL); } catch(Exception ignore) {}
}
if (!started.get()) {
throw new IOException("JavaFX did not start");
}
}
@Override
public void start(Stage primaryStage) {
started.set(true);
log.fine("Started JavaFX, creating WebView...");
stage = primaryStage;
primaryStage.setScene(new Scene(webView = new WebView()));
// Add listener for SUCCEEDED
Worker<Void> worker = webView.getEngine().getLoadWorker();
worker.stateProperty().addListener(stateListener);
// Prevents JavaFX from shutting down when hiding window, useful for calling capture(...) in succession
Platform.setImplicitExit(false);
}
/** Listens for a SUCCEEDED state to activate image capture **/
private static ChangeListener<Worker.State> stateListener = (ov, oldState, newState) -> {
if (newState == Worker.State.SUCCEEDED) {
WritableImage snapshot = webView.snapshot(new SnapshotParameters(), null);
capture.set(SwingFXUtils.fromFXImage(snapshot, null));
finished.set(true);
stage.hide();
}
};
/** Listen for failures **/
private static ChangeListener<Throwable> exceptListener = new ChangeListener<Throwable>() {
@Override
public void changed(ObservableValue<? extends Throwable> obs, Throwable oldExc, Throwable newExc) {
if (newExc != null) { thrown.set(newExc); }
}
};
/** Loads the specified HTML, triggering stateListener above **/
public static synchronized BufferedImage capture(final String html) throws Throwable {
capture.set(null);
thrown.set(null);
finished.set(false);
// run these actions on the JavaFX thread
Platform.runLater(new Thread(() -> {
try {
webView.getEngine().loadContent(html, "text/html");
stage.show(); // JDK-8087569: will not capture without showing stage
stage.toBack();
}
catch(Throwable t) {
thrown.set(t);
}
}));
// wait for capture to complete by monitoring our own finished flag
while(!finished.get() && thrown.get() == null) {
log.fine("Waiting on capture...");
try {
Thread.sleep(CAPTURE_SLEEP_INTERVAL);
}
catch(InterruptedException e) {
log.warning(e.getLocalizedMessage());
}
}
if (thrown.get() != null) {
throw thrown.get();
}
return capture.get();
}
}
相关:
- 完整网页加载到JavaFX WebView组件中的屏幕截图,不仅是可见部分。
- 我能通过编程方式捕获场景快照吗?
- Java中的整个页面截图
- JavaFX 2.0+ WebView /WebEngine将网页呈现为图像
- 在javafx中设置舞台和场景的高度和宽度
- JavaFX:在使用webview时如何调整舞台大小
- 正确调整嵌入Tabelcell的Webview的大小
- https://docs.oracle.com/javase/8/javafx/embedded-browser-tutorial/add-browser.htm#CEGDIBBI
- http://docs.oracle.com/javafx/2/swing/swing-fx-interoperability.htm#CHDIEEJE
- https://bugs.openjdk.java.net/browse/JDK-8126854
- https://bugs.openjdk.java.net/browse/JDK-8087569
Platform.runLater
并且没有解决问题。如果您不同意,请自行尝试。如果我错了,我会很高兴关闭这个问题。 - tresfSUCCEEDED
状态(其中侦听器在FX线程上触发)是正确的技术。如果有一种方法可以显示排队的事件,我会很高兴尝试。我在Oracle论坛的评论和一些SO问题中找到了零散的建议,即WebView
必须按设计在其自己的线程中运行,因此经过数天的测试,我正在集中精力解决这个问题。如果这个假设是错误的,那太好了。我愿意接受任何合理的建议,以在没有任意等待时间的情况下解决问题。 - tresfloadContent
方法或加载文件URL时才会发生这种情况。 - VGR