2012-05-07 55 views
3

請看下面的三個文件。JTextPane:突出顯示註釋行

Form.java 

    package Normal;  

import Keywords.JavaKeywords;  
import java.awt.Color;  
import java.awt.Dimension;  
import java.awt.FlowLayout;  
import java.awt.event.ActionEvent;  
import java.awt.event.ActionListener;  
import java.util.ArrayList;  
import java.util.List;  
import java.util.logging.Level;  
import java.util.logging.Logger;  
import javax.swing.*;  
import javax.swing.text.*;  

    public class Form extends JEditorPane  
    {  
     private JTextPane textPane;  
     private JPanel south;  
     private JScrollPane scroll;  
     private List<String> keywords, literals;  
     private String content;  
     public String documentType;     
     private Style style, style2;    
     private KeywordConnector java;    
     private DefaultStyledDocument document;   
     int start, end, offset1,length1;   
     private JButton button;    
     JFrame frame;  


     public Form()  
     {  
      super();  
       frame = new JFrame();  

      //Declaring the instance variables  
      textPane = new JTextPane();  
      textPane.setMinimumSize(new Dimension(100,100));  

      button = new JButton("Save");  
      button.addActionListener(new Action());  

      document = (DefaultStyledDocument) textPane.getDocument();   
      document.setDocumentFilter(new HighlightFilter());  

      keywords = new ArrayList();  
      literals = new ArrayList();  

      //Adding Styles  
      style = document.addStyle("blue", null);   
      StyleConstants.setForeground(style, Color.BLUE);      
      style2 = document.addStyle("red", null);  
      StyleConstants.setForeground(style2, Color.RED);     

      //Creating the main window  
      south = new JPanel();  
      south.setLayout(new FlowLayout());  
      south.add(button);       
      scroll = new JScrollPane(textPane);  

      frame.getContentPane().add(scroll,"Center");  
      frame.getContentPane().add(south,"South");     
      frame.setVisible(true);  
      frame.setSize(800,600);  
      frame.validate();  
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       
     }  

     private class HighlightFilter extends DocumentFilter  
     {   

     public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)   
       throws BadLocationException {   
      if (string.isEmpty()) {   
      fb.insertString(offset, string, attr);    


      } else {   
      super.insertString(fb, offset, string, attr);   
      offset1 = offset;  
      length1 = string.length()+offset;  
      System.out.println(string.length());  

      System.out.println("Offset: "+offset1+" Length: "+length1);  
      highlight();   
      }   
     }   

     public void remove(FilterBypass fb, int offset, int length)   
       throws BadLocationException {   
      if (length == 0) {   
      fb.remove(offset, length);   
      } else {   
      super.remove(fb, offset, length);   
      offset1 = offset;  
      length1 = length;  
      System.out.println("Offset: "+offset1+" Length: "+length1);  
      highlight();   
      }   
     }   

     public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)   
       throws BadLocationException {   
      if (length == 0 && text.isEmpty()) {   
      fb.replace(offset, length, text, attrs);   
      } else {   
      super.replace(fb, offset, length, text, attrs);   
      offset1 = offset;  
      length1 = length;  
      System.out.println("Offset: "+offset1+" Length: "+length1);  
      highlight();  
      } } }  

     private void highlight()  
     {   
       SwingUtilities.invokeLater(new Runnable()  
       {   
        int next=0; int end=0;  

       @Override   
       public void run() {   
        try {   
         //content = document.getText(0, document.getLength());  

         int preWord =Utilities.getPreviousWord(textPane, offset1);  

         if(preWord<0)  
         {  
          preWord=preWord*-1;  
         }  
         System.out.println("Previous Word: "+preWord);  

         int wordEnd = Utilities.getWordEnd(textPane, offset1);  

         System.out.println("Word End: "+wordEnd);  

         System.out.println("The Text: "+document.getText(preWord,wordEnd-preWord));  

         content = document.getText(preWord,(wordEnd-preWord)-1);  

         System.out.println("Length: "+(wordEnd-preWord));  

        for (String word : content.split("\\s")) {   
        next = content.indexOf(word, next);   
        end = next + word.length();   

        document.setCharacterAttributes(preWord, word.length(),   
        textPane.getStyle(keywords.contains(word) ? "blue" : literals.contains(word)? "red":"default"),true);   
        next = end;   
       }   
       } catch (BadLocationException ex) {   
       ex.printStackTrace();   
       }   
      }   
      });   
      }  

     private class Action implements ActionListener  
     {  
      public void actionPerformed(ActionEvent ae)  
      {      
       java = new JavaKeywords();    
       keywords = java.getKeywords();  
       literals = java.getLiterals();  


       int next=0; int end=0;  
      try {  
       content = document.getText(0, document.getLength());  
      } catch (BadLocationException ex) {  
       Logger.getLogger(Form.class.getName()).log(Level.SEVERE, null, ex);  
      }  

       for (String word : content.split("\\s")) {   
        next = content.indexOf(word, next);   
        end = next + word.length();   

        document.setCharacterAttributes(next, end,   
        textPane.getStyle(keywords.contains(word) ? "blue" : literals.contains(word)? "red":"default"),true);   
        next = end;   
       }   
      }  
     }  

     public static void main(String[] args) throws Exception {  
      SwingUtilities.invokeLater(new Runnable()  
      {   
       @Override   
       public void run() {   
       Form f = new Form();  
       }   
      });   
      }  
    } 

Keywords.java

package Keywords;  

    import Normal.KeywordConnector;  
    import java.util.ArrayList;  
    import java.util.List;  
    import keywords.Literals;  

    public class JavaKeywords implements KeywordConnector  
    {  
     private ArrayList list, literals;  

     public JavaKeywords()  
     {  
      //Default Keywords  
      list = new ArrayList();  

      list.add("abstract");  
      list.add("assert");    
      list.add("break");  
      list.add("byte");  
      list.add("case");  
      list.add("catch");  
      list.add("char");  
      list.add("class");  


      //Literals  
      String string = "String";  

      literals = new ArrayList();  
      literals.add(string);  
      literals.add("bool");  
      literals.add("int");  
      literals.add("Double");  
      literals.add("float");  
      literals.add("char");  
      literals.add("long");  
      literals.add("byte");  

     }  


     @Override  
     public ArrayList getKeywords()  
     {  
      return list;  
     }  

     @Override  
     public List<String> getLiterals()  
     {  
      return literals;  
     }  

     @Override  
     public List getOthers() {  
      throw new UnsupportedOperationException("Not supported yet.");  
     }  

    }  

KeywordConnector.java

package Normal; 
import java.util.List; 

public interface KeywordConnector 
{ 
    public List<String> getKeywords(); 
    public List<String> getLiterals(); 
    public List<String> getOthers(); 
} 

這到底是怎麼發生的,當用戶點擊保存按鈕,程序會搜索的Java關鍵字,並開始凸顯他們。正如你所看到的,這個程序沒有辦法突出註釋行!我正在努力實現這個目標超過一週。

我可以在「//」符號和「/ *」「*」符號添加到關鍵字列表中,但隨後發生的事情是,

  1. 當輸入註釋行,我得檢查評論中的字母數量。那麼只有我可以突出顯示所有這些(或者我可以突出顯示整個行,但是您知道它最終的樣子)。但是,如果我將它添加到關鍵字,我不能這樣做。

  2. 當評論「符號」被刪除,整個有色意見函已被更改爲「無顏色」

所以,我怎麼可以添加註釋亮點支持,實現上述兩個提到?

請幫我解決這個問題!謝謝...

+5

你的問題到底是太不具體。你不能轉儲一段代碼,並要求「給我解決方案」。你必須首先分離出一個特定的問題並且清楚地解釋它。 –

+0

另外,請不要_shout_;使用_italics_或(不太常用)** bold **來強調。 – trashgod

+0

@IngoKegel *「您的問題是......」* ..不可見?什麼是問題? –

回答

3

它添加到Form.actionPerformed(動作事件)方法

Pattern singleLinecommentsPattern = Pattern.compile("\\/\\/.*"); 
Matcher matcher = singleLinecommentsPattern.matcher(content); 

while (matcher.find()) { 
    document.setCharacterAttributes(matcher.start(), 
     matcher.end() - matcher.start(), textPane.getStyle("red"), true); 
} 

Pattern multipleLinecommentsPattern = Pattern.compile("\\/\\*.*?\\*\\/", 
         Pattern.DOTALL); 
matcher = multipleLinecommentsPattern.matcher(content); 

while (matcher.find()) { 
    document.setCharacterAttributes(matcher.start(), 
     matcher.end() - matcher.start(), textPane.getStyle("red"), true); 
} 
+1

正則表達式使用上面的湖一些嚴重的測試,他們只是涵蓋了明顯的情況。 – Zecas

+0

嗨,非常感謝您的代碼,我非常感謝。但是,有一個小問題。我的Form.java文件中沒有「actionPerformed(ActionEvent)」方法。所以,我將它添加到「dataCaller」方法和「高亮」方法。但是,它不起作用,它沒有突出任何東西。請幫忙!! –

+0

是的,你說得對。我的意思是添加到方法的結尾Form.Action.actionPerformed – Zecas