0
我想在JTextPane中做一些基本的格式化。为此我决定使用html(HTMLDocument和HTMLEditorKit)。格式化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>
谢谢,我不相信解决方案很容易。我花了大约3个小时弄清楚了这一点...... – 2013-03-25 13:35:40