Search code examples
javaxmlswingjtextpanebold

Make a selected word bold in the text of a HTML-styled JtextPane?


How can I get the selected word in the text from a JTextPane and then apply the Bold property for the selected-text by using the Ctrl+B Short Cut.

String are given to the JTextpane from the xml files. String are get from the tag elements and set to the JTextpane:

String selectedText = ta_textpane.getSelectedText();
int getselectedtextstart = ta_textpane.getSelectionStart();
int getselectedtextend = ta_textpane.getSelectionEnd();

String textbef = text.substring(0, getselectedtextstart);
String textaft = text.substring(getselectedtextend, text.length());
String textinbet = "<b>" + text.substring(getselectedtextstart,getselectedtextend) + "</b>";

String settoxmlfiletag = textbef + textinbet + textaft

After concat the bold(<b>), write the bolded string to the xml tag. i have a Problem in getting the last index position and first index position because i use the tamil language in the JTextPane

Bold is applied but cannot be applied in the correct position.


Solution

  • A good solution is to use the insertHTML() method from HTMLEditorKit:

    public class Bold extends JTextPane {       
    
        public Bold(){
            super();
    
            setEditorKit(new HTMLEditorKit());
            setText("<html><h1>Example</h1><p>Just a test</p></html>");
            getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_B, KeyEvent.CTRL_MASK), "bold");
            getActionMap().put("bold", new AbstractAction(){
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    JTextPane bold = (JTextPane) e.getSource();
                    int start = bold.getSelectionStart();
                    int end = bold.getSelectionEnd();
                    String txt = bold.getSelectedText();
                    if(end != start)
                        try {
                            bold.getDocument().remove(start, end-start);
                            HTMLEditorKit htmlkit = (HTMLEditorKit) bold.getEditorKit();
                            htmlkit.insertHTML((HTMLDocument) bold.getDocument(), start, "<b>"+txt+"</b>", 0, 0, HTML.Tag.B);
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                }
    
            });
        }
    
        public static void main(String[] args){
            SwingUtilities.invokeLater(()->{
                JFrame f = new JFrame();
                f.setContentPane(new Bold());
                f.setPreferredSize(new Dimension(640,480));
                f.pack();
                f.setVisible(true); 
            });
        }
    }