2016-04-03 4 views
0

Ich habe ein paar Probleme mit der Highlighter-Klasse in meinem textArea. Mein Programm sollte so funktionieren:Textmarker hebt den gesamten textArea anstelle eines bestimmten Wortes und seiner Vorkommen hervor [java]

In einem textArea erkennt das Programm eine Zeichenfolge, die in der ersten Zeile platziert werden soll (die mit "#" markierten Zeilen der Kommentare werden nicht berücksichtigt), markiert und all seine Vorkommen in der gesamten textArea.

Beispiel:

#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 

Mein Code, sondern hebt nur das alle Textarea. Hier ist mein Code.

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     
} 

Antwort

1

nicht sicher, ob ich genau wissen, wie Sie das Programm mögen, arbeiten, aber hier sind, wie ich es interpretiert:

Die erste Zeile, die nicht mit # startet ein Schlüsselwort enthält, und dieses Schlüsselwort sollte im gesamten Text hervorgehoben.

Dies muss nicht so kompliziert sein wie der Code, den Sie derzeit haben. Sie müssen nur das Schlüsselwort finden, dann alle Vorkommen von ihm finden und sie hervorheben.

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

  Und dann haben Sie

findKeyWord(); 

in alle Zuhörer Funktionen

keyWord = findKeyWord(); 
+0

danke für y ändern du antwortest! aber immer noch, wenn ich den Text ohne "#" beginne, wird der ganze Text hervorgehoben! – Pino

+0

Ah ok, jetzt denke ich, ich weiß was du meinst. Ich habe den Code in meiner Antwort aktualisiert, um zu sehen, ob es jetzt funktioniert. – BadCash

+0

es hebt den gesamten Text hervor D: – Pino

Verwandte Themen