Set local image in JavaFX HTMLeditor

I am looking for a way to use the JavaFX HTMLEditor setHtmlText to add a local image. I can add the remote image without problems:

HTMLEditor editor = new HTMLEditor();  
    editor.setHtmlText("<img src=\"http://someaddress.com\" width=\"32\" height=\"32\" >");

but cannot do this for a local image

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

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

+4
source share
3 answers

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

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

It works the same as loading content into a WebView , as in:

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


Here is a screenshot:

editorwithimage

And 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();
    editor.setHtmlText(
      "<img src=\"" + 
         getClass().getResource("Blue-Fish-icon.png") + 
      "\" width=\"32\" height=\"32\" >"
    );
    stage.setScene(new Scene(editor));
    stage.show();
  }

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

, - ?

. , . , JavaFX: HTMLEditor WebView contenteditable true , JavaScript.

JavaFX, WebView HTMLEditor, , .

+4

: :\\ .

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

This code inserts the image before the last-end tag or the body tag tag.

String imgUrl = "http://..../image.png";
StringBuilder sb = new StringBuilder(htmlEditor.getHtmlText());
int pos = sb.lastIndexOf("</p>") > -1 ? sb.lastIndexOf("</p>") : sb.lastIndexOf("</body>");
sb.insert(pos, "<span><img src='" + imgUrl + "'></span>");
htmlEditor.setHtmlText(sb.toString());
0
source

All Articles