如何从 JTextPane
中获取文本中选定的单词然后使用 Ctrl+B
对所选文本应用粗体属性捷径。
字符串被赋予JTextpane
来自 xml 文件。字符串从标签元素获取并设置为 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 标记。我在获取最后一个索引位置和第一个索引位置时遇到问题,因为我使用 tamil
JTextPane
中的语言
已应用粗体,但无法应用在正确的位置。
最佳答案
一个好的解决方案是使用 HTMLEditorKit
中的 insertHTML()
方法:
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);
});
}
}
关于java - 将 HTML 样式的 JtextPane 文本中的选定单词设为粗体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32241960/