Java JTextPane-HTMLDocument:添加/删除新样式时,其他属性也会更改
我有一个JTextPane(或JEditorPane),我想在其中添加一些按钮来格式化文本(如图所示) 当我将所选文本更改为粗体(创建新样式)时,字体族(和其他属性)也会更改。为什么?我想在所选文本中设置(或删除)粗体属性,其他属性保持不变 这就是我正在尝试的:Java JTextPane-HTMLDocument:添加/删除新样式时,其他属性也会更改,java,styles,jtextpane,jeditorpane,dom,Java,Styles,Jtextpane,Jeditorpane,Dom,我有一个JTextPane(或JEditorPane),我想在其中添加一些按钮来格式化文本(如图所示) 当我将所选文本更改为粗体(创建新样式)时,字体族(和其他属性)也会更改。为什么?我想在所选文本中设置(或删除)粗体属性,其他属性保持不变 这就是我正在尝试的: private void setBold(boolean flag){ HTMLDocument doc = (HTMLDocument) editorPane.getDocument(); int start = ed
private void setBold(boolean flag){
HTMLDocument doc = (HTMLDocument) editorPane.getDocument();
int start = editorPane.getSelectionStart();
int end = editorPane.getSelectedText().length();
StyleContext ss = doc.getStyleSheet();
//check if BoldStyle exists and then add / remove it
Style style = ss.getStyle("BoldStyle");
if(style == null){
style = ss.addStyle("BoldStyle", null);
style.addAttribute(StyleConstants.Bold, true);
} else {
style.addAttribute(StyleConstants.Bold, false);
ss.removeStyle("BoldStyle");
}
doc.setCharacterAttributes(start, end, style, true);
}
但正如我上面解释的,其他属性也会发生变化:
任何帮助都将不胜感激。提前谢谢
您可以使用以下两行代码中的一行来完成所要做的事情:
newstylededitorkit.BoldAction().actionPerformed(null)代码>
editorPane.getActionMap().get(“font bold”).actionPerformed(null)代码>
。。。其中editorPane当然是JEditorPane的一个实例。
两者都将无缝地处理已定义的任何属性,并支持文本选择
关于您的代码,它不适用于以前的样式文本,因为您将不使用任何内容覆盖相应的属性。我的意思是,您永远不会使用(例如)集合为当前选定文本设置的属性的值。因此,您实际上是将它们重置为全局样式表指定的默认值
好消息是,如果您使用上面的一个片段,您不需要担心所有这些。希望能有所帮助。我对您的代码做了一些小的修改,它在这里工作:
private void setBold(boolean flag){
HTMLDocument doc = (HTMLDocument) editorPane.getDocument();
int start = editorPane.getSelectionStart();
int end = editorPane.getSelectionEnd();
if (start == end) {
return;
}
if (start > end) {
int life = start;
start = end;
end = life;
}
StyleContext ss = doc.getStyleSheet();
//check if BoldStyle exists and then add / remove it
Style style = ss.getStyle(editorPane.getSelectedText());
if(style == null){
style = ss.addStyle(editorPane.getSelectedText(), null);
style.addAttribute(StyleConstants.Bold, true);
} else {
style.addAttribute(StyleConstants.Bold, false);
ss.removeStyle(editorPane.getSelectedText());
}
doc.setCharacterAttributes(start, end - start, style, true);
}
private void setBold(boolean flag){
HTMLDocument doc = (HTMLDocument) editorPane.getDocument();
int start = editorPane.getSelectionStart();
int end = editorPane.getSelectionEnd();
if (start == end) {
return;
}
if (start > end) {
int life = start;
start = end;
end = life;
}
StyleContext ss = doc.getStyleSheet();
//check if BoldStyle exists and then add / remove it
Style style = ss.getStyle(editorPane.getSelectedText());
if(style == null){
style = ss.addStyle(editorPane.getSelectedText(), null);
style.addAttribute(StyleConstants.Bold, true);
} else {
style.addAttribute(StyleConstants.Bold, false);
ss.removeStyle(editorPane.getSelectedText());
}
doc.setCharacterAttributes(start, end - start, style, true);
}