2017-08-23 4 views
0

J'ai ce code de java2s.com et je viens de le modifier. Je ne sais pas si j'ai besoin d'utiliser le runnable ou le documentlistener pour que l'application surligne automatiquement le mot qui a été défini dans le code. Je n'ai pas beaucoup de connaissances sur les deux, j'ai essayé le runnable mais j'ai rencontré des erreurs. Est-ce que quelqu'un peut m'aider? Voici le code.met automatiquement en surbrillance les mots dans le panneau de texte

public class Sample { 
public static void main(String[] args) { 
    JFrame f = new JFrame(); 
    JTextPane textPane = new JTextPane(); 
    String word = ""; 

Highlighter highlighter = new UnderlineHighlighter(null); 

textPane.setHighlighter(highlighter); 
textPane.setText("This is a test"); 

final WordSearcher searcher = new WordSearcher(textPane); 
final UnderlineHighlighter uhp = new UnderlineHighlighter(Color.red); 
    String w = "i"; 
    int offset = searcher.search(w); 
    if (offset == -1) { 
    return; 
    } 
    try { 
    textPane.scrollRectToVisible(textPane.modelToView(offset)); 
    } catch (BadLocationException ex) { 
    } 

textPane.getDocument().addDocumentListener(new DocumentListener() { 
    @Override 
    public void insertUpdate(DocumentEvent evt) { 
    searcher.search(word); 
    } 

    @Override 
    public void removeUpdate(DocumentEvent evt) { 
    searcher.search(word); 
    } 

    @Override 
    public void changedUpdate(DocumentEvent evt) { 
    } 
}); 
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
//f.add(panel, "South"); 
f.add(new JScrollPane(textPane), "Center"); 
f.setSize(400, 400); 
f.setVisible(true); 
} 
public static String word; 

public static Highlighter highlighter = new UnderlineHighlighter(null); 
} 

class WordSearcher { 
public WordSearcher(JTextComponent comp) { 
this.comp = comp; 
this.painter = new UnderlineHighlighter.UnderlineHighlightPainter(
    Color.red); 
} 
public int search(String word) { 
    int firstOffset = -1; 
    Highlighter highlighter = comp.getHighlighter(); 


Highlighter.Highlight[] highlights = highlighter.getHighlights(); 
for (int i = 0; i < highlights.length; i++) { 
    Highlighter.Highlight h = highlights[i]; 
    if (h.getPainter() instanceof 
UnderlineHighlighter.UnderlineHighlightPainter) { 
    highlighter.removeHighlight(h); 
    } 
} 

if (word == null || word.equals("")) { 
    return -1; 
} 


String content = null; 
try { 
    Document d = comp.getDocument(); 
    content = d.getText(0, d.getLength()).toLowerCase(); 
} catch (BadLocationException e) { 
    // Cannot happen 
    return -1; 
} 

word = word.toLowerCase(); 
int lastIndex = 0; 
int wordSize = word.length(); 

while ((lastIndex = content.indexOf(word, lastIndex)) != -1) { 
    int endIndex = lastIndex + wordSize; 
    try { 
    highlighter.addHighlight(lastIndex, endIndex, painter); 
    } catch (BadLocationException e) { 
    // Nothing to do 
    } 
    if (firstOffset == -1) { 
    firstOffset = lastIndex; 
    } 
    lastIndex = endIndex; 
} 

return firstOffset; 
} 

protected JTextComponent comp; 

protected Highlighter.HighlightPainter painter; 

} 

class UnderlineHighlighter extends DefaultHighlighter { 
public UnderlineHighlighter(Color c) { 
painter = (c == null ? sharedPainter : new UnderlineHighlightPainter(c)); 
} 


public Object addHighlight(int p0, int p1) throws BadLocationException { 
return addHighlight(p0, p1, painter); 
} 

public void setDrawsLayeredHighlights(boolean newValue) { 
// Illegal if false - we only support layered highlights 
if (newValue == false) { 
    throw new IllegalArgumentException(
     "UnderlineHighlighter only draws layered highlights"); 
} 
super.setDrawsLayeredHighlights(true); 
} 

public static class UnderlineHighlightPainter extends 
    LayeredHighlighter.LayerPainter { 
public UnderlineHighlightPainter(Color c) { 
    color = c; 
} 

public void paint(Graphics g, int offs0, int offs1, Shape bounds, 
    JTextComponent c) { 
    // Do nothing: this method will never be called 
} 

public Shape paintLayer(Graphics g, int offs0, int offs1, Shape bounds, 
    JTextComponent c, View view) { 
    g.setColor(color == null ? c.getSelectionColor() : color); 

    Rectangle alloc = null; 
    if (offs0 == view.getStartOffset() && offs1 == view.getEndOffset()) { 
    if (bounds instanceof Rectangle) { 
     alloc = (Rectangle) bounds; 
    } else { 
     alloc = bounds.getBounds(); 
    } 
    } else { 
    try { 
     Shape shape = view.modelToView(offs0, 
      Position.Bias.Forward, offs1, 
      Position.Bias.Backward, bounds); 
     alloc = (shape instanceof Rectangle) ? (Rectangle) shape 
      : shape.getBounds(); 
    } catch (BadLocationException e) { 
     return null; 
    } 
    } 

    FontMetrics fm = c.getFontMetrics(c.getFont()); 
    int baseline = alloc.y + alloc.height - fm.getDescent() + 1; 
    g.drawLine(alloc.x, baseline, alloc.x + alloc.width, baseline); 
    g.drawLine(alloc.x, baseline + 1, alloc.x + alloc.width, 
     baseline + 1); 

    return alloc; 
} 

protected Color color; // The color for the underline 
} 


protected static final Highlighter.HighlightPainter sharedPainter = new 
UnderlineHighlightPainter(
    null); 

protected Highlighter.HighlightPainter painter; 
} 
+0

Quelle est exactement votre question? Vous aviez besoin d'aide pour résoudre vos erreurs? – user3437460

+0

Veuillez inclure votre stacktrace dans votre question – Ascalonian

Répondre

0

Votre code a peut-être des erreurs d'importation? Il fonctionne très bien avec Java 1.8. Dans cette situation, il est correct d'utiliser DocumentListener. Fait quelques modifications dans la classe principale pour trouver le texte "test":

import javax.swing.*; 
import javax.swing.event.DocumentEvent; 
import javax.swing.event.DocumentListener; 
import javax.swing.text.*; 
import java.awt.*; 

public class Sample { 
public static void main(String[] args) { 
     JFrame f = new JFrame(); 
     JTextPane textPane = new JTextPane(); 
     String word = "test"; 

     Highlighter highlighter = new UnderlineHighlighter(null); 

     textPane.setHighlighter(highlighter); 
     textPane.setText("This is a test"); 

     final WordSearcher searcher = new WordSearcher(textPane); 
     final UnderlineHighlighter uhp = new UnderlineHighlighter(Color.red); 
     String w = "i"; 
     int offset = searcher.search(w); 
     if (offset == -1) { 
       return; 
     } 
     try { 
       textPane.scrollRectToVisible(textPane.modelToView(offset)); 
     } catch (BadLocationException ex) { 
     } 

     textPane.getDocument().addDocumentListener(new DocumentListener() { 
       @Override 
       public void insertUpdate(DocumentEvent evt) { 
         searcher.search(word); 
       } 

       @Override 
       public void removeUpdate(DocumentEvent evt) { 
         searcher.search(word); 
       } 

       @Override 
       public void changedUpdate(DocumentEvent evt) { 
       } 
     }); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.add(new JScrollPane(textPane), "Center"); 
     f.setSize(400, 400); 
     f.setVisible(true); 
     searcher.search(word); 
    } 

    public static String word; 

    public static Highlighter highlighter = new UnderlineHighlighter(null); 
} 
}