2013-03-25 16 views
0

我想在JTextPane中做一些基本的格式化。爲此我決定使用html(HTMLDocument和HTMLEditorKit)。格式化HTMLEditorKit

這裏是按鈕的動作偵聽器的代碼,應該使選定的文本加粗

boldButton.addActionListener(new ActionListener(){ 

      @Override 
      public void actionPerformed(ActionEvent arg0) { 

        System.out.print(outputTextPane.getSelectedText()); 

         int offset = outputTextPane.getSelectionStart(); 
         int length = outputTextPane.getSelectionEnd()-outputTextPane.getSelectionStart(); 
         String content = ""; 
         try { 
          content = outputDoc.getText(offset, length); 
         } catch (BadLocationException e1) { 
          // TODO Auto-generated catch block 
          e1.printStackTrace(); 
         }     
         try { 
          outputDoc.replace(offset, length, "", null); 
          outputKit.insertHTML(outputDoc, outputTextPane.getSelectionStart(), "<b>"+content+"</b>", 0, 0, HTML.Tag.B); 

         } catch (BadLocationException | IOException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
         } 

      } 

     }); 

它的工作原理除了當你嘗試大膽的文本還強調了(基本上相同的動作偵聽器)。源代碼看起來是這樣,那麼:

text -> select "text" and press bold button 
<b>text</b> -> select "x" and press underline button 
<b>te</b><u>x</u><b>t</b> 

回答

3

這裏是按鈕的動作偵聽器的代碼,應該使選定的文本加粗

不要創建自己的操作。使用編輯器工具包提供的操作。例如:

JButton bold = new JButton(new StyledEditorKit.BoldAction()); 
+0

謝謝,我不相信解決方案很容易。我花了大約3個小時弄清楚了這一點...... – 2013-03-25 13:35:40