从特定word-Java中删除突出显示

从特定word-Java中删除突出显示,java,swing,highlight,jtextarea,swing-highlighter,Java,Swing,Highlight,Jtextarea,Swing Highlighter,我想构建一个示例,从匹配我的应用程序过滤器的单词中删除突出显示。因此,我基于以下样本: public void removeHighlights(JTextComponent jTextArea) { Highlighter hilite = jTextArea.getHighlighter(); Highlighter.Highlight[] hilites = hilite.getHighlights(); for (int i =

我想构建一个示例,从匹配我的应用程序过滤器的单词中删除突出显示。因此,我基于以下样本:

    public void removeHighlights(JTextComponent jTextArea) {

        Highlighter hilite = jTextArea.getHighlighter();
        Highlighter.Highlight[] hilites = hilite.getHighlights();

        for (int i = 0; i < hilites.length; i++) {
            if (hilites[i].getPainter() instanceof TextHighLighter) {
                hilite.removeHighlight(hilites[i]);
            }
        }
    } 
public void removeHighlights(JTextComponent jTextArea){
Hiliter hilite=jTextArea.getHighlighter();
hilliter.Highlight[]hilites=hilite.getHighlights();
for(int i=0;i
此示例用于删除文本区域的所有高光。例如,如果我有三个选定的单词,并且我取消选中其中一个单词的复选框,那么所有的过滤器都将被删除,我只想删除未选中单词的突出部分。。有没有一种简单的方法来检查哪个单词与过滤器匹配?或者我需要手动操作吗?因为直到现在我才发现我的研究没有成功

提前谢谢

最终编辑:

基于@camickr答案的逻辑适用于我:

public void removeHighlights(JTextComponent jTextArea, String turnLightOff) {


           Highlighter hilite = jTextArea.getHighlighter();

           Highlighter.Highlight[] hilites = hilite.getHighlights();

           for (int i = 0; i < hilites.length; i++) {

              int wordLenght = hilites[i].getEndOffset() - hilites[i].getStartOffset();

              if(wordLenght == turnLightOff.length()){

                  if (hilites[i].getPainter() instanceof TextHighLighter) {

                      hilite.removeHighlight(hilites[i]);
              }

              }
           }                
}
public void removeHighlights(JTextComponent jTextArea,字符串关闭){
Hiliter hilite=jTextArea.getHighlighter();
hilliter.Highlight[]hilites=hilite.getHighlights();
for(int i=0;i
  • 查看有关添加/删除Highlighter/instanceof myHighLighter的简单示例

导入java.awt.BorderLayout;
导入java.awt.Color;
导入java.awt.FontMetrics;
导入java.awt.Graphics;
导入java.awt.Rectangle;
导入java.awt.Shape;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入javax.swing.JFrame;
导入javax.swing.JLabel;
导入javax.swing.JPanel;
导入javax.swing.JScrollPane;
导入javax.swing.JTextField;
导入javax.swing.JTextPane;
导入javax.swing.UIManager;
导入javax.swing.event.DocumentEvent;
导入javax.swing.event.DocumentListener;
导入javax.swing.text.BadLocationException;
导入javax.swing.text.DefaultHighlighter;
导入javax.swing.text.Document;
导入javax.swing.text.Highlighter;
导入javax.swing.text.JTextComponent;
导入javax.swing.text.LayeredHighlighter;
导入javax.swing.text.Position;
导入javax.swing.text.View;
公共类HighlightExample{
公共静态void main(字符串[]args){
UIManager.put(“TextPane.caretForeground”,颜色为黄色);
UIManager.put(“TextPane.selectionBackground”,颜色.绿色);
UIManager.put(“TextPane.selection前台”,Color.blue);
/*试一试{
UIManager.setLookAndFeel(“com.sun.java.swing.plaf.windows.WindowsLookAndFeel”);
}捕获(异常evt){
}*/
JFrame f=新JFrame(“突出显示示例”);
最终JTextPane textPane=新JTextPane();
textPane.setHighlighter(荧光灯);
textPane.setText(“此文本窗格不包含html。它支持字母包装,”
+\n此文本窗格不包含html。它支持换行
+\n此文本窗格不包含html。它支持换行
+\n此文本窗格不包含html。它支持换行
+\n此文本窗格不包含html。它支持换行
+“\n此文本窗格不包含html。它支持换行!”;
JPanel窗格=新的JPanel();
setLayout(新的BorderLayout());
添加(新JLabel(“输入单词,然后按回车键:”),“West”);
最终JTextField=newjtextfield(“包装”);
窗格。添加(tf,“中间”);
f、 添加(窗格,“南”);
f、 添加(新的JScrollPane(文本窗格),“中心”);
/*试一试{
read(新文件阅读器(“links1.html”),null;
}捕获(例外e){
System.out.println(“加载文件失败”+args[0]);
系统输出打印ln(e);
}*/
final WordSearcher searcher=新WordSearcher(文本窗格);
tf.addActionListener(新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件evt){
word=tf.getText().trim();
int offset=searcher.search(单词);
如果(偏移量!=-1){
试一试{
textPane.scrollRectToVisible(文本窗格
.modelToView(偏移量);
}捕获(错误位置异常e){
}
}
}
});
textPane.getDocument().addDocumentListener(新DocumentListener()){
@凌驾
公共作废插入更新(DocumentEvent evt){
搜索者。搜索(word);
}
@凌驾
公共作废移除更新(DocumentEvent evt){
搜索者。搜索(word);
}
@凌驾
公共作废更改日期(DocumentEvent evt){
}
});
f、 设置大小(400400);
f、 setVisible(真);
}
公共静态字符串字;
公共静态高亮灯=新的下划线高亮灯(空);
}
//在中搜索单词的简单类
//文档并突出显示该单词的出现
类字搜索器{
公共单词搜索器(JTextComponent comp){
this.comp=comp;
this.painter=新的UnderlineHighlighter.UnderlineHighlightPainter(
颜色(红色);
}
//搜索单词并返回单词的偏移量
//第一次出现。将为所有项目添加高光
//发现的事件。
公共整数搜索(字符串字)
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;
import javax.swing.text.LayeredHighlighter;
import javax.swing.text.Position;
import javax.swing.text.View;

public class HighlightExample {

    public static void main(String[] args) {
        UIManager.put("TextPane.caretForeground", Color.yellow);
        UIManager.put("TextPane.selectionBackground", Color.green);
        UIManager.put("TextPane.selectionForeground", Color.blue);
        /*try {
         UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
         } catch (Exception evt) {
         }*/
        JFrame f = new JFrame("Highlight example");
        final JTextPane textPane = new JTextPane();
        textPane.setHighlighter(highlighter);
        textPane.setText("This text pane contains no html. It supports letter wrapping, "
                + "\nThis text pane contains no html. It supports letter wrapping!, "
                + "\nThis text pane contains no html. It supports letter wrapping!, "
                + "\nThis text pane contains no html. It supports letter wrapping!, "
                + "\nThis text pane contains no html. It supports letter wrapping!, "
                + "\nThis text pane contains no html. It supports letter wrapping!");
        JPanel pane = new JPanel();
        pane.setLayout(new BorderLayout());
        pane.add(new JLabel("Enter word, then press ENTER key: "), "West");
        final JTextField tf = new JTextField("wrapping!");
        pane.add(tf, "Center");
        f.add(pane, "South");
        f.add(new JScrollPane(textPane), "Center");
        /*try {
         textPane.read(new FileReader("links1.html"), null);
         } catch (Exception e) {
         System.out.println("Failed to load file " + args[0]);
         System.out.println(e);
         }*/
        final WordSearcher searcher = new WordSearcher(textPane);
        tf.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                word = tf.getText().trim();
                int offset = searcher.search(word);
                if (offset != -1) {
                    try {
                        textPane.scrollRectToVisible(textPane
                                .modelToView(offset));
                    } catch (BadLocationException e) {
                    }
                }
            }
        });
        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.setSize(400, 400);
        f.setVisible(true);
    }
    public static String word;
    public static Highlighter highlighter = new UnderlineHighlighter(null);
}

// A simple class that searches for a word in
// a document and highlights occurrences of that word
class WordSearcher {

    public WordSearcher(JTextComponent comp) {
        this.comp = comp;
        this.painter = new UnderlineHighlighter.UnderlineHighlightPainter(
                Color.red);
    }

    // Search for a word and return the offset of the
    // first occurrence. Highlights are added for all
    // occurrences found.
    public int search(String word) {
        int firstOffset = -1;
        Highlighter highlighter = comp.getHighlighter();
        // Remove any existing highlights for last word
        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;
        }
        // Look for the word we are given - insensitive search
        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));
    }

    // Convenience method to add a highlight with
    // the default painter.
    public Object addHighlight(int p0, int p1) throws BadLocationException {
        return addHighlight(p0, p1, painter);
    }

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

    // Painter for underlined highlights
    public static class UnderlineHighlightPainter extends LayeredHighlighter.LayerPainter {

        public UnderlineHighlightPainter(Color c) {
            color = c;
        }

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

        @Override
        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
    }
    // Shared painter used for default highlighting
    protected static final Highlighter.HighlightPainter sharedPainter = new UnderlineHighlightPainter(
            null);
    // Painter used for this highlighter
    protected Highlighter.HighlightPainter painter;
}
highlighter.removeAllHighlights();