【问题标题】:JTextPane: Highlighting Comment LinesJTextPane:突出显示注释行
【发布时间】:2012-05-15 19:09:00
【问题描述】:

请看下面三个文件。

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

关键字.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. 当评论“符号”被删除时,整个彩色评论字母必须更改为“无颜色”

那么,如何添加评论高亮支持以实现上述两个提及?

请帮我解决这个问题!!谢谢...

【问题讨论】:

  • 你的问题太不具体了。您不能转储一段代码并询问“给我解决方案”。你必须先隔离一个具体的问题,然后解释清楚。
  • 另外,请不要大喊;使用 斜体 或(不太常见)bold 表示强调。
  • @IngoKegel “你的问题是……” ..隐形?问题是什么?
  • 大家好,感谢您的回复。 @Ingo Kegel:嗨,实际上我将代码减少到了我能做到的最高水平。 Form.Java 是 1820 行代码,所以我已尽力减少代码并隔离问题 :) 如果给我带来任何不便,请原谅我 :) @transhgod:嗨,我很抱歉我犯的错误。我还是新来的,所以我肯定有很多东西要学:)。谢谢你的出现:)
  • @Andrew:如果我的问题不是很清楚,请原谅我。所以,我的问题是“如何添加评论突出显示支持以实现提到的两个选项?”

标签: java swing editor highlight jtextpane


【解决方案1】:

将此添加到 Form.actionPerformed(ActionEvent) 方法的末尾

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

【讨论】:

  • Lake 上面使用的正则表达式进行了一些严肃的测试,它们只是涵盖了明显的情况。
  • 您好,非常感谢您的代码,非常感谢。但是,有一个小问题。我的 Form.java 文件中没有“actionPerformed(ActionEvent)”方法。所以,我将它添加到“dataCaller”方法和“highlight”方法中。但是,它没有用,它没有突出任何东西。请帮忙!!
  • 是的,你是对的。我的意思是添加到 Form.Action.actionPerformed 方法的末尾
  • 非常感谢您的代码!有效!对此,我真的非常感激!!但是,有一个问题,我想你也可以帮助我。仅当我将用户的 java 代码复制并粘贴到窗口中,然后按“保存”按钮时,此代码才有效。但是,我也需要在用户输入时突出显示它们。请帮忙!
  • 非常感谢您的回答!我也设法在用户输入时突出显示代码!我将您的代码放入一个方法中,并使用以下代码在“highlight”方法中调用它 if(documentType.endsWith(".java") && word.equals("/") || word.equals"*") {高亮评论();这是工作!再次感谢!
猜你喜欢
  • 2013-11-14
  • 2011-08-06
  • 1970-01-01
  • 2011-07-21
  • 2012-04-04
  • 1970-01-01
  • 2016-10-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多