代码之家  ›  专栏  ›  技术社区  ›  Sriram S

在HTML样式的JtextPane的文本中将所选单词加粗?

  •  2
  • Sriram S  · 技术社区  · 9 年前

    如何从 JTextPane 然后使用 Ctrl+B 捷径。

    字符串指定给 JTextpane 从xml文件中。字符串从标记元素中获取并设置为 J文本窗格 :

    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
    

    凹入后 bold(<b>) ,将粗体字符串写入xml标记。我在获取最后一个索引位置和第一个索引位置时遇到问题,因为我使用 tamil 语言 文本窗格

    粗体已应用,但无法在正确位置应用。

    2 回复  |  直到 9 年前
        1
  •  2
  •   Eric Leibenguth    9 年前

    一个好的解决方案是使用 insertHTML() 方法来自 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
  •  2
  •   Sharcoux    8 年前

    选择文本后,只需拨打 HTMLEditorKit.BoldAction.actionPerformed .

    InsertHTML 也是一个很好的解决方案,但在某些情况下,参数可能会有问题。