问题
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?
回答1:
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:
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();
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?
- With JavaFX 2, you can embed images mixed with text into a FlowPane as described in Javafx Text multi-word colorization.
- 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.
回答2:
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+"<img src='file:\\\\"+imagePath+"' >" );
回答3:
This code insert image before the last end paragraph tag or end body 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());
来源:https://stackoverflow.com/questions/15802619/set-a-local-image-in-javafx-htmleditor