2013-04-04 137 views
4

我正在寻找一种方法来使用JavaFX HTMLEditor的setHtmlText来添加本地图像。我可以添加一个远程图像没有问题:在JavaFX中设置本地图像HTMLeditor

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

但对于一个局部图像

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

这个按钮是在同一水平Java源无法做到这一点。那么为什么不能这样工作?

回答

4

使用getResource获取本地图像资源的位置。

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

它的工作方式加载的内容同进WebView为:

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


这里有一个截图:

editorwithimage

而且可执行样本:

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); } 
} 

我只是好奇,如果这是得到的图像变成某种文本区域的唯一途径?

  1. 使用JavaFX 2,则如在Javafx Text multi-word colorization描述可以嵌入文本混合的图象分成一FlowPane
  2. Java 8添加了一个TextFlow组件,它允许您将图像嵌入文本区域。

上述两种技术都仅用于数据显示。既不允许编辑插入图像和其他节点的多样式文本。目前,JavaFX平台为此功能提供的唯一控件是HTMLEditorWebView,其中contenteditable true或嵌入式3rd party editor written in JavaScript

对于不依赖于WebView或HTMLEditor的create styled text editors using native JavaFX构造,已经有了一些第三方的努力,但到目前为止,我认为没有任何东西可以广泛使用。

+0

btw我也很好奇,如果这是获得图像到某种文本区域的唯一方法? – Matt 2013-04-04 22:40:35

+1

根据附加问题更新了答案 - 您可能想尝试将'contenteditable'设置为true的'WebView'。 – jewelsea 2013-04-04 23:00:06

2

示例代码:追加文件:\\在图片标签中引用本地文件。

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

好主意,这就是为什么我投票给你 – Muhammad 2014-10-24 17:46:42

0

此代码在最后一段末尾段落标记或尾段标记前插入图片。

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());