2014-10-11 99 views
-4

我正在開發一種用於java語言的自編的java編輯器。我在使代碼縮進時遇到問題。我正在使用JTextArea鍵入代碼,並且我希望它在每個支架後增加縮進並在每個支架後減少縮進。請幫幫我。JTextArea中的縮進代碼

+0

考慮以下來源作爲研究選項,也許縮進不會是構建良好文本編輯器的唯一困難。 http://texteditors.org/cgi-bin/wiki.pl?JavaBasedEditors – Insanovation 2014-10-11 12:30:41

回答

1

當輸入特定字符時,您可能需要實現DocumentFilter以處理特殊處理。

這是一個處理換行符的例子。當換行符被發現的「白色空間」將被添加到文檔,使文本的左邊緣前行相匹配:

import java.awt.*; 
import javax.swing.*; 
import javax.swing.text.*; 

public class NewLineFilter extends DocumentFilter 
{ 
    public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) 
     throws BadLocationException 
    { 
     if ("\n".equals(str)) 
      str = addWhiteSpace(fb.getDocument(), offs); 

     super.insertString(fb, offs, str, a); 
    } 

    public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) 
     throws BadLocationException 
    { 
     if ("\n".equals(str)) 
      str = addWhiteSpace(fb.getDocument(), offs); 

     super.replace(fb, offs, length, str, a); 
    } 

    private String addWhiteSpace(Document doc, int offset) 
     throws BadLocationException 
    { 
     StringBuilder whiteSpace = new StringBuilder("\n"); 
     Element root = doc.getDefaultRootElement(); 
     int line = root.getElementIndex(offset); 
     int length = doc.getLength(); 

     for (int i = root.getElement(line).getStartOffset(); i < length; i++) 
     { 
      String temp = doc.getText(i, 1); 

      if (temp.equals(" ") || temp.equals("\t")) 
      { 
       whiteSpace.append(temp); 
      } 
      else 
       break; 
     } 

     return whiteSpace.toString(); 
    } 
    private static void createAndShowUI() 
    { 
     JTextArea textArea = new JTextArea(5, 50); 
     AbstractDocument doc = (AbstractDocument)textArea.getDocument(); 
     doc.setDocumentFilter(new NewLineFilter()); 

     JFrame frame = new JFrame("NewLineFilter"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.add(new JScrollPane(textArea)); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) 
    { 
     EventQueue.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       createAndShowUI(); 
      } 
     }); 
    } 
} 

在你的情況下,代碼是相似的。當您找到「{」時,您想要插入「\ n」,然後添加空格,然後爲縮進添加其他字符。

我希望它在每個{括號之後增加縮進並在每個}括號之後減少縮進。

此外,不是單獨處理「{」「}」,另一種方法是隻處理「{」。然後你會添加一個空行並同時添加「}」。這樣你就可以確保你總是有一對匹配的括號。