Monday 10 November 2014

Hyperlink Button in HtmlEditor

Hello Friends, In this post I am gonna show you how to add hyperlink button in JavaFX HtmlEditor and make it work to insert hyperlink in HtmlEditor. Here I am not gonna create complete application instead I am giving you specific code which would add hyperlink button to HtmlEditor and that button would do its task. You can use this Code according to your need.
Code to create HtmlEditor Object and add Hyperlink Button and add event handler:-
HTMLEditor editor = new HTMLEditor();
Node node = editor.lookup(".top-toolbar");
if (node instanceof ToolBar) {
ToolBar bar = (ToolBar) node;
Button btn = new Button("Hyperlink");
ImageView iv = new javafx.scene.image.ImageView(new Image(getClass().getResourceAsStream("/images/hyperlink.png")));
btn.setMinSize(26.0, 22.0);
btn.setMaxSize(26.0, 22.0);
iv.setFitHeight(16);
iv.setFitWidth(16);
btn.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
btn.setGraphic(iv);
btn.setTooltip(new javafx.scene.control.Tooltip("Hyperlink"));
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
String url = JOptionPane.showInputDialog("Enter Url");
WebView webView = (WebView) editor.lookup("WebView");
String selected = (String) webView.getEngine().executeScript("window.getSelection().toString();");
String hyperlinkHtml = "<a href=\"" + url.trim() + "\" title=\"" + selected + "\" target=\"_blank\">" + selected + "</a>";
webView.getEngine().executeScript(getInsertHtmlAtCurstorJS(hyperlinkHtml));
}
});
bar.getItems().add(btn);

getInsertHtmlAtCurstorJS Code:-
private String getInsertHtmlAtCurstorJS(String html){
return "insertHtmlAtCursor('" + html + "');"
+ "function insertHtmlAtCursor(html) {\n"
+ " var range, node;\n"
+ " if (window.getSelection && window.getSelection().getRangeAt) {\n"
+ " window.getSelection().deleteFromDocument();\n"
+ " range = window.getSelection().getRangeAt(0);\n"
+ " node = range.createContextualFragment(html);\n"
+ " range.insertNode(node);\n"
+ " } else if (document.selection && document.selection.createRange) {\n"
+ " document.selection.createRange().pasteHTML(html);\n"
+ " document.selection.clear();"
+ " }\n"
+ "}";
}
Hyperlink Button in HtmlEditor
Thank You Friends
If you like this please share