Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

javafx webview loaded but not rendered yet before snapshot

therealkencSep 9 2013 — edited Sep 10 2013

Hi. I need to take a snapshot of a web page that was just loaded with WebView. Immediately after the WebEngine LoadWorker's notification fires, I call WebView.snapshot(). Unfortunately, the page has loaded, but it doesn't appear to be rendered into the Scene at the instant I take the snapshot. After a full day of trial-and-error (mostly error) I managed to get it to work by sleeping for 50ms before taking the snapshot. This as it turns out is a royal pain in practice because WebView wants to be called only from the main JavaFX Application thread, and I appears I to need to get out of the present JavaFX Application thread (from the notifier) in order for WebView to do it's rendering thing.

Is there any way to find out when a newly loaded page has actually finished rendering into WebView? Yes I know there is no such thing as finished since there could be animations going. But I would at least like to know when the newly loaded DOM has been rendered "for the first time". Or is there some other way to do what I am trying to accomplish without the magic sleep, and without so many ugly lines of code?

  Thread snapshotThread = new Thread(new Runnable() {

    @Override

    public void run() {

      try {

        Thread.sleep(50);  // !!! Here is the magic

      } catch (InterruptedException e1) {

        throw new IllegalStateException(e1);

      }

      final Ref<Image> ref = new Ref<Image>(null);

      final CountDownLatch imageLatch = new CountDownLatch(1);

      Platform.runLater(new Runnable() {

        @Override

        public void run() {

          SnapshotParameters params = new SnapshotParameters();

          ref.set(webView.snapshot(params, null));

          imageLatch.countDown();

        }

      });

     try {

        imageLatch.await();

      } catch (InterruptedException e2) {

        throw new IllegalStateException(e2);

      }

      ByteArrayOutputStream baos = new ByteArrayOutputStream();

      try {

        ImageIO.write(SwingFXUtils.fromFXImage(ref.get(), null), "png", baos);

      } catch (IOException e) {

        throw new IllegalStateException(e);

      }


      String name = webView.getEngine().getLocation() + " " + (new Date()).toString();

      RegisteredImage ra = new RegisteredImage(key, name, "image/png", baos.toByteArray());

      ImageRegistrar.register(ra);       

    }

  });


  snapshotThread.start();


Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 8 2013
Added on Sep 9 2013
9 comments
12,131 views