我做了一个扩展HTMLEditor的自定义htmleditor。 我删除了一些按钮,并添加了一些。
现在,我想添加几个按钮,以将键入的文本更改为1种特定颜色。 但是我找不到在按钮的setOnAction中更改文本颜色的方法。 我尝试了几种方法。
1:我在光标位置插入的html
2:设置htmleditor颜色的颜色选择器
(jsCodeInsertHtml字符串允许在光标处显示html)
String jsCodeInsertHtml = "function insertHtmlAtCursor(html) {\n" +
" var range, node;\n" +
" if (window.getSelection && window.getSelection().getRangeAt) {\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" +
" }\n" +
"}insertHtmlAtCursor('####html####')";
// add a custom button to the top toolbar.
Node nodetop = editor.lookup(".top-toolbar");
if (nodetop instanceof ToolBar) {
ToolBar topbar = (ToolBar) nodetop;
//var1 color
ImageView graphic = new ImageView(var1pic);
Button colorVar1Button = new Button("", graphic);
colorVar1Button.setFocusTraversable(false);
colorVar1Button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
WebView webView=(WebView)editor.lookup("WebView");
WebEngine engine= webView.getEngine();
//try 1
engine.executeScript(jsCodeInsertHtml.replace("####html####","<p><span style=\"color: rgb(200, 200, 200); caret-color: rgb(200, 200, 200);\">"));
//the HTML is inserted , but no colorchange. i tryed some htmlvariants aswel
//try 2
Node color = editor.lookup(".html-editor-foreground");
((ColorPicker)color).setValue(Color.rgb(200,200,200));
// i notice the button change in the colorpicker ,
// but no change in color happens
topbar.getItems().addAll(colorVar1Button);
答案 0 :(得分:0)
找到了解决方案。我只需要触发Collorpicker的actionevent使其起作用
colorVar1Button.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
Node color = editor.lookup(".html-editor-foreground");
((ColorPicker)color).setValue(Color.HOTPINK);
color.fireEvent(new ActionEvent());
}
});
topbar.getItems().addAll(colorVar1Button);