JavaFX的文档状态,一个WebView
当准备Worker.State.SUCCEEDED
达到但是,除非你稍等片刻(即Animation
,Transition
,PauseTransition
等等),一个空白页面的呈现方式。
这表明在WebView内部发生了一个事件,准备将其捕获,但这是什么?
GitHub上SwingFXUtils.fromFXImage
有7,000多个使用的代码片段,但其中大多数似乎与无关WebView
,是交互式的(人为掩盖种族条件)或使用任意的Transitions(从100ms到2,000ms的任何地方)。
我试过了:
在的尺寸
changed(...)
范围内进行监听WebView
(height和width属性DoubleProperty
实现ObservableValue
,可以监视这些东西)- 🚫不可行。有时,该值似乎与绘制例程分开更改,从而导致部分内容。
盲目地告诉
runLater(...)
FX应用程序线程上的所有内容。- techniques许多技术都使用此方法,但是我自己的单元测试(以及其他开发人员的一些反馈)解释说,事件通常已经在正确的线程上,并且此调用是多余的。我能想到的最好的办法就是通过排队,对某些人起作用而增加了足够的延迟。
将DOM侦听器/触发器或JavaScript侦听器/触发器添加到
WebView
- despite
SUCCEEDED
尽管捕获了空白,但在调用JavaScript和DOM时似乎都正确加载了。DOM / JavaScript侦听器似乎无济于事。
- despite
使用
Animation
或Transition
来有效地“休眠”而不会阻塞主FX线程。
什么时候可以打电话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
经过测试,无法解决。如果您不同意,请自己尝试。我很乐意犯错,这将解决问题。
SUCCEEDED
状态(侦听器在FX线程上激发状态)是适当的技术。如果有一种方法可以显示排队的事件,我很乐意尝试。通过在Oracle论坛上的评论以及一些WebView
必须按设计在其自己的线程中运行的SO问题,我发现了稀疏的建议,因此经过几天的测试,我将精力集中在那里。如果这个假设是错误的,那就太好了。我愿意接受任何合理的建议来解决问题,而无需等待时间。
loadContent
方法或加载文件URL时发生。