Reputation: 87
I have read many threads on JTextPane and it made me start writing a little text editor using JTextPane, but in the middle of the project am almost folding up! Please can some one explain to me how i can insert an html character int a textpane like
JTextPane pane = new JtextPane();
pane.settext("¢");
My problem is that if i have already keyed in some text and I then use the settext
mathod to insert a special character on the same line of text then the special character is inserted while the previous text disappears. How can I stop that happening?
Upvotes: 0
Views: 557
Reputation: 19161
You haven't said when you want to call setText
. If you want to do it in response to a button click, then you just need to:
grabFocus
to put the focus and input caret back into the text pane.The code would look like this:
JButton btnAdd = new JButton("add");
jPanel1.add(btnAdd);
btnAdd.addActionListener(new ActionListener(){
@Override public void actionPerformed(ActionEvent arg0) {
String text = pane.getText();
pane.setText(text + "¢");
pane.grabFocus();
}
});
If you are working with HTMLDocument (you haven't posted your full code, so it is not clear what you are doing to produce HTML), you could do something like:
pane = new JTextPane();
jPanel1.add(pane);
final HTMLEditorKit kit = new HTMLEditorKit();
final HTMLDocument doc = new HTMLDocument();
pane.setEditorKit(kit);
pane.setDocument(doc);
...
btnAdd.addActionListener(new ActionListener(){
@Override public void actionPerformed(ActionEvent arg0) {
int start = pane.getSelectionStart();
try {
// add a span containing the desired element inside the current paragraph or other containing element
kit.insertHTML(doc, start, "<span>¢</span>", 0, 0, HTML.Tag.SPAN);
} catch ...
pane.grabFocus();
}
});
Upvotes: 2