I have a JTextComponent in which a user can enter text in two ways:
- He can type text directly into it.
- Using a second control, he can indirectly insert text into it. This is done by programmatically calling insertString().
The font used in the text inserted in the second way will be different than the font that is typed in directly. The font of the text typed in will be the default font of the JTextComponent.
Here is the code. The TODO is what I don't know how to do.
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.
}
}
}
Is there a way to reset the attributes back to what they originally were?