自动突出显示文本窗格中的单词

时间:2017-08-23 13:00:05

标签: java user-interface textarea jtextarea

我有来自java2s.com的代码,我刚修改了它。我不知道是否需要使用runnable或documentlistener,以便应用程序自动突出显示代码中定义的单词。我对这两个没有太多了解,我尝试了runnable但我遇到了错误。有人能帮我吗?这是代码。

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

1 个答案:

答案 0 :(得分:0)

也许你的代码有一些导入错误?它与Java 1.8一起运行良好。在这种情况下,使用DocumentListener是好的。在主要课程中进行了一些修改以找到文本&#34; test&#34;:

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