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

旧时模样 提交于 2020-01-05 03:07:46

问题


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.


回答1:


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); 
        });
    }
}



回答2:


When your text is selected, just call HTMLEditorKit.BoldAction.actionPerformed.

InsertHTML is also a good solution, but the parameters can be problematic in some circumstances.



来源:https://stackoverflow.com/questions/32241960/make-a-selected-word-bold-in-the-text-of-a-html-styled-jtextpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!