我正在尝试在 JTextPane 中进行一些基本的格式化。为此,我决定使用 html(HTMLDocument 和 HTMLEditorKit)。
这是按钮的动作监听器代码,应该使选定的文本变为粗体
boldButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.print(outputTextPane.getSelectedText());
int offset = outputTextPane.getSelectionStart();
int length = outputTextPane.getSelectionEnd()-outputTextPane.getSelectionStart();
String content = "";
try {
content = outputDoc.getText(offset, length);
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
outputDoc.replace(offset, length, "", null);
outputKit.insertHTML(outputDoc, outputTextPane.getSelectionStart(), "<b>"+content+"</b>", 0, 0, HTML.Tag.B);
} catch (BadLocationException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
除非您尝试使粗体文本也加下划线(基本上相同的动作侦听器),否则它可以工作。源代码如下所示:
text -> select "text" and press bold button
<b>text</b> -> select "x" and press underline button
<b>te</b><u>x</u><b>t</b>