荧光笔突出显示所有textArea而不是特定单词及其出现[java]

时间:2016-04-03 11:07:02

标签: java jtextarea swing-highlighter

我在textArea中使用荧光笔类时遇到一些问题。 我的程序应该这样工作:

在textArea中,程序检测到应放在第一行的字符串(注释行,标记为“#”,不考虑),在整个textArea中突出显示它及其出现的所有内容。

示例:

#this is an example code
#these line are comments
 **whateverWordIsFine**  #this is the word to highlight
 //code
 //code
 **whateverWordIsFine** #occurrence to be highlighted
 //
 // 
 **whateverWordIsFine** #occurrence to be highlighted

我的代码只是突出显示所有textArea。 这是我的代码。

import java.awt.Color;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;



public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() throws BadLocationException {
        initComponents();

        textArea.getDocument().addDocumentListener(new DocumentListener() {
            String keyWord = findKeyWord();
            @Override
            public void insertUpdate(DocumentEvent e) {
                try {
                    findOccurrences();
                } catch (BadLocationException ex) {
                    Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                try {
                    findOccurrences();
                } catch (BadLocationException ex) {
                    Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                try {
                    findOccurrences();
                } catch (BadLocationException ex) {
                    Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            public String findKeyWord() throws BadLocationException {
                if (textArea.getText().isEmpty())
                    return "";

                String keyWord = "";

                for( String line : textArea.getText().split("\n")){
                    if( !line.startsWith("#") ){
                        int keywordEndPosition = line.indexOf("#");
                        keyWord = line.substring(0, keywordEndPosition == -1 ? line.length() : keywordEndPosition);
                        keyWord = keyWord.trim();
                        break;
                    }
                }

                return keyWord;

            }

            public void findOccurrences() throws BadLocationException {
                Highlighter highlighter = textArea.getHighlighter();
                DefaultHighlighter.DefaultHighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.CYAN);

                highlighter.removeAllHighlights();

                if (keyWord.isEmpty())
                     return;
                Pattern pattern = Pattern.compile( Pattern.quote(keyWord) );
                Matcher matcher = pattern.matcher(textArea.getText());  

                while(matcher.find()) {
                    highlighter.addHighlight(matcher.start(), matcher.end(), painter);
                }

            }


        });


    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        textArea = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        textArea.setColumns(20);
        textArea.setRows(5);
        jScrollPane1.setViewportView(textArea);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 417, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new NewJFrame().setVisible(true);
                } catch (BadLocationException ex) {
                    Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea textArea;
    // End of variables declaration                   
}

1 个答案:

答案 0 :(得分:1)

我不确定我是否完全理解你希望程序如何工作,但这是我解释它的方式:

不以#开头的第一行包含关键字,此关键字应在整个文本中突出显示。

这不必像您目前的代码那么复杂。您只需找到关键字,然后找到它的所有匹配项并突出显示它们。

public String findKeyWord() throws BadLocationException {
    if( textArea.getText().isEmpty() )
        return "";

    String keyWord = "";
    for( String line : textArea.getText().split("\n")){
        if( !line.startsWith("#") ){
            int keywordEndPosition = line.indexOf("#"); 
            keyWord = line.substring(0, keywordEndPosition == -1 ? line.length() : keywordEndPosition );
            keyWord = keyWord.trim();
            break;
        }
    }

    return keyWord;
}

public void findOccurrences() throws BadLocationException {  
    Highlighter highlighter = textArea.getHighlighter();        
    DefaultHighlighter.DefaultHighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.CYAN);

    highlighter.removeAllHighlights();        

    if( keyWord.isEmpty() )
        return;

    Pattern pattern = Pattern.compile( Pattern.quote(keyWord) );
    Matcher matcher = pattern.matcher(textArea.getText());                    

    while(matcher.find()) {
        highlighter.addHighlight(matcher.start(), matcher.end(), painter);
    }
}

然后你必须改变

findKeyWord();

在所有侦听器函数中

keyWord = findKeyWord();