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:
- Read the text from the (captured variable for the) pane
- Append your desired character
- (Optionally) use
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();
}
});