Ityav
Ityav

Reputation: 87

How to insert a html special character in a JTextPane

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

Answers (1)

Andy Brown
Andy Brown

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:

  1. Read the text from the (captured variable for the) pane
  2. Append your desired character
  3. (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>&cent;</span>", 0, 0, HTML.Tag.SPAN);
        } catch ...
        pane.grabFocus();
    }               
});

Upvotes: 2

Related Questions