我正在尝试用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>发布于 2013-03-25 11:28:49
这里是按钮的操作侦听器的代码,它应该将选定的文本设置为粗体
不要创建你自己的Action。使用编辑器工具包提供的操作。例如:
JButton bold = new JButton( new StyledEditorKit.BoldAction() );https://stackoverflow.com/questions/15606622
复制相似问题