Set a local image in JavaFX HTMLeditor


I'm looking for a way to use JavaFX HTMLEditor's setHtmlText to add a local image. I can add a remote image no problem:

HTMLEditor editor = new HTMLEditor();  
    editor.setHtmlText("<img src=\"\" width=\"32\" height=\"32\" >");

but can't do this for a local image

HTMLEditor editor = new HTMLEditor();  
    editor.setHtmlText("<img src=\"categoryButton.fw.png\" width=\"32\" height=\"32\" >");

This button is on the same level as the java source. So why won't this work?

4/4/2013 4:38:04 AM

Accepted Answer

Use getResource to get the location of the local image resource.

  "<img src=\"" + 
     getClass().getResource("categoryButton.fw.png") + 
  "\" width=\"32\" height=\"32\" >"

It works the same way as loading content into WebView as in:

How to reach css and image files from the html page loaded by javafx.scene.web.WebEngine#loadContent?

Here is an screenshot:


And an executable sample:

import javafx.application.*;
import javafx.scene.Scene;
import javafx.scene.web.HTMLEditor;
import javafx.stage.Stage;

public class HTMLEditorWithImage extends Application {
  @Override public void start(Stage stage) {
    HTMLEditor editor = new HTMLEditor();
      "<img src=\"" + 
         getClass().getResource("Blue-Fish-icon.png") + 
      "\" width=\"32\" height=\"32\" >"
    stage.setScene(new Scene(editor));;

  public static void main(String[] args) { launch(args); }

I was just curious if this was the only way of getting an image into a some sort of text area?

  1. With JavaFX 2, you can embed images mixed with text into a FlowPane as described in Javafx Text multi-word colorization.
  2. Java 8 adds a TextFlow component which allows you to embed an image into a text region.

Both of the above techniques are for data display only. Neither allow for editing of the multi-styled text with images and other nodes inserted in it. For now, the only controls provided by the JavaFX platform for this functionality are the HTMLEditor or a WebView with contenteditable true or an embedded 3rd party editor written in JavaScript.

There have been some 3rd party efforts to create styled text editors using native JavaFX constructs that don't rely on WebView or HTMLEditor, but as of today I don't think any are ready for widespread use.

5/23/2017 12:09:02 PM

Sample Code: Append file:\\ in the image tag to refer a local file.

ScreenCapture x = new ScreenCapture();
String imagePath = x.captureScreen(scCaptureCount+++"", "C:\\work\\temp");
String text = editor.getHtmlText();
editor.setHtmlText(text+"&lt;img src='file:\\\\"+imagePath+"' >" );

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow