我正在尝试在 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();
}
}
});
它可以工作,除非您尝试使粗体文本也带有下划线(基本上相同的 Action 监听器)。源代码如下所示:
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>
最佳答案
Here is code of action listener of button that should make selected text bold
不要创建自己的操作。使用编辑器工具包提供的操作。例如:
JButton bold = new JButton( new StyledEditorKit.BoldAction() );
关于java - 格式化 HTMLEditorKit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15606622/