问题描述
如何从JTextPane
获取文本中的所选单词,然后使用Ctrl+B
快捷键将Bold属性应用于所选文本.
How can I get the selected word in the text from a JTextPane
and then apply the Bold property for the selected-text by using the Ctrl+B
Short Cut.
字符串从xml文件提供给JTextpane
.字符串是从标记元素获取的,并设置为JTextpane
:
String are given to the JTextpane
from the xml files. String are get from the tag elements and set to the JTextpane
:
String selectedText = ta_textpane.getSelectedText();
int getselectedtextstart = ta_textpane.getSelectionStart();
int getselectedtextend = ta_textpane.getSelectionEnd();
String textbef = text.substring(0, getselectedtextstart);
String textaft = text.substring(getselectedtextend, text.length());
String textinbet = "<b>" + text.substring(getselectedtextstart,getselectedtextend) + "</b>";
String settoxmlfiletag = textbef + textinbet + textaft
在连接bold(<b>)
之后,将加粗的字符串写入xml标记.我在获取最后一个索引位置和第一个索引位置时遇到问题,因为我在JTextPane
After concat the bold(<b>)
, write the bolded string to the xml tag. i have a Problem in getting the last index position and first index position because i use the tamil
language in the JTextPane
已应用粗体,但无法将其应用在正确的位置.
Bold is applied but cannot be applied in the correct position.
推荐答案
一个好的解决方案是使用HTMLEditorKit
中的insertHTML()
方法:
A good solution is to use the insertHTML()
method from HTMLEditorKit
:
public class Bold extends JTextPane {
public Bold(){
super();
setEditorKit(new HTMLEditorKit());
setText("<html><h1>Example</h1><p>Just a test</p></html>");
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_B, KeyEvent.CTRL_MASK), "bold");
getActionMap().put("bold", new AbstractAction(){
@Override
public void actionPerformed(ActionEvent e) {
JTextPane bold = (JTextPane) e.getSource();
int start = bold.getSelectionStart();
int end = bold.getSelectionEnd();
String txt = bold.getSelectedText();
if(end != start)
try {
bold.getDocument().remove(start, end-start);
HTMLEditorKit htmlkit = (HTMLEditorKit) bold.getEditorKit();
htmlkit.insertHTML((HTMLDocument) bold.getDocument(), start, "<b>"+txt+"</b>", 0, 0, HTML.Tag.B);
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
}
public static void main(String[] args){
SwingUtilities.invokeLater(()->{
JFrame f = new JFrame();
f.setContentPane(new Bold());
f.setPreferredSize(new Dimension(640,480));
f.pack();
f.setVisible(true);
});
}
}
这篇关于在HTML样式的JtextPane的文本中将所选单词设为粗体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!