【发布时间】:2011-08-22 18:09:20
【问题描述】:
我有一个 JTextComponent,用户可以在其中通过两种方式输入文本:
- 他可以直接在里面输入文字。
- 使用第二个控件,他可以间接地将文本插入其中。这是通过以编程方式调用 insertString() 来完成的。
第二种方式插入的文本中使用的字体将与直接输入的字体不同。输入文本的字体将是 JTextComponent 的默认字体。
这里是代码。 TODO 是我不知道该怎么做的。
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
public class ResetAttributesInDocument extends JApplet {
private ButtonListener bl = new ButtonListener();
private JTextPane myJTextComponent;
public void init() {
JPanel contentPanel = new JPanel(new BorderLayout());
myJTextComponent = new JTextPane();
contentPanel.add(myJTextComponent, BorderLayout.CENTER);
JButton insertTextButton = new JButton("Insert text");
insertTextButton.addActionListener(bl);
contentPanel.add(insertTextButton, BorderLayout.SOUTH);
getContentPane().add(contentPanel);
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
final Document doc = myJTextComponent.getDocument();
final int caretPosition = myJTextComponent.getCaretPosition();
SimpleAttributeSet set = new SimpleAttributeSet();
StyleConstants.setFontFamily(set, "Courier New");
// Possibly add more attributes to set here.
try {
doc.insertString(caretPosition, "text in Courier New", set);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
// TODO Reset the attributes back to what they originally were so
// that any new text the user enters after the inserted text is in
// the original font.
}
}
}
有没有办法将属性重置回原来的样子?
【问题讨论】: