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=\"http://someaddress.com\" 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?
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 way as loading content into WebView as in:
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();
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); }
}
I was just curious if this was the only way of getting an image into a some sort of text area?
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.