Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何取消JTextPane中文本的高亮显示_Java_Swing_Jtextpane - Fatal编程技术网

Java 如何取消JTextPane中文本的高亮显示

Java 如何取消JTextPane中文本的高亮显示,java,swing,jtextpane,Java,Swing,Jtextpane,我编写了一个代码,在JTextPane中查找单词。这里的问题是,当我输入一个搜索词并单击搜索按钮时,它会突出显示给定搜索词的所有出现。我想突出显示第一次出现的单词,然后点击搜索按钮显示第二次出现的方式,就像这样。另一个问题是,当点击文本窗格时,搜索完成后,它并没有取消高亮显示 我的代码: public class FindAWord extends javax.swing.JFrame { public static void main(String args[]) {

我编写了一个代码,在
JTextPane
中查找单词。这里的问题是,当我输入一个搜索词并单击搜索按钮时,它会突出显示给定搜索词的所有出现。我想突出显示第一次出现的单词,然后点击搜索按钮显示第二次出现的方式,就像这样。另一个问题是,当点击文本窗格时,搜索完成后,它并没有取消高亮显示

我的代码:

public class FindAWord extends javax.swing.JFrame {

    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(MarkAll.class.getName()).log(
                    java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MarkAll.class.getName()).log(
                    java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MarkAll.class.getName()).log(
                    java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MarkAll.class.getName()).log(
                    java.util.logging.Level.SEVERE, null, ex);
        }
        // </editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new MarkAll().setVisible(true);
            }
        });
    }

    Highlighter.HighlightPainter myHighLightPainter = new FindAWord.MyHighightPainter(
            Color.LIGHT_GRAY);
    // Variables declaration - do not modify
    private javax.swing.JScrollPane scrollPane;
    private javax.swing.JTextField searchText;
    private javax.swing.JTextPane textPane;
    private javax.swing.JButton search;

    public FindAWord() {
        initComponents();
    }

    public void removeHighLights(JTextComponent component) {
        Highlighter hilet = component.getHighlighter();
        Highlighter.Highlight[] highLites = hilet.getHighlights();
        for (int i = 0; i < highLites.length; i++) {
            if (highLites[i].getPainter() instanceof MarkAll.MyHighightPainter) {
                hilet.removeHighlight(highLites[i]);
            }
        }
    }

    public void highLight(JTextComponent component, String patteren) {
        try {
            removeHighLights(component);
            Highlighter hLite = component.getHighlighter();
            Document doc = component.getDocument();
            String text = component.getText(0, doc.getLength());
            int pos = 0;
            while ((pos = text.toUpperCase().indexOf(patteren.toUpperCase(),
                    pos)) >= 0) {
                hLite.addHighlight(pos, pos + patteren.length(),
                        myHighLightPainter);
                pos += patteren.length();
            }
        } catch (Exception e) {
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        search = new javax.swing.JButton();
        searchText = new javax.swing.JTextField();
        scrollPane = new javax.swing.JScrollPane();
        textPane = new javax.swing.JTextPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        search.setText("Search");
        search.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchActionPerformed(evt);
            }
        });

        scrollPane.setViewportView(textPane);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
                getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                        layout.createSequentialGroup()
                        .addGap(36, 36, 36)
                        .addComponent(search,
                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                91,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(32, 32, 32)
                                .addComponent(searchText,
                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                        120,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addContainerGap(114, Short.MAX_VALUE))
                                        .addGroup(
                                                javax.swing.GroupLayout.Alignment.TRAILING,
                                                layout.createSequentialGroup().addComponent(scrollPane)
                                                .addContainerGap()));
        layout.setVerticalGroup(layout
                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(
                        layout.createSequentialGroup()
                        .addGap(36, 36, 36)
                        .addGroup(
                                layout.createParallelGroup(
                                        javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(search)
                                        .addComponent(
                                                searchText,
                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addPreferredGap(
                                                        javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                        .addComponent(scrollPane,
                                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                235, Short.MAX_VALUE)));

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

    private void searchActionPerformed(java.awt.event.ActionEvent evt) {
        if (searchText.getText().length() == 0) {
            removeHighLights(textPane);
        } else
            highLight(textPane, searchText.getText());
    }

    class MyHighightPainter extends DefaultHighlighter.DefaultHighlightPainter {
        MyHighightPainter(Color color) {
            super(color);
        }
    }
}
公共类FindAWord扩展了javax.swing.JFrame{
公共静态void main(字符串参数[]){
/*设置Nimbus的外观和感觉*/
// 
/*
*如果Nimbus(在JavaSE6中引入)不可用,请使用
*默认外观。有关详细信息,请参阅
* http://download.oracle.com/javase
*/tutorial/uiswing/lookandfeel/plaf.html
*/
试一试{
对于(javax.swing.UIManager.LookAndFeelInfo:javax.swing.UIManager
.getInstalledLookAndFeels()){
if(“Nimbus”.equals(info.getName())){
setLookAndFeel(info.getClassName());
打破
}
}
}捕获(ClassNotFoundException ex){
java.util.logging.Logger.getLogger(MarkAll.class.getName()).log(
java.util.logging.Level.SEVERE,null,ex);
}catch(实例化异常){
java.util.logging.Logger.getLogger(MarkAll.class.getName()).log(
java.util.logging.Level.SEVERE,null,ex);
}捕获(非法访问例外){
java.util.logging.Logger.getLogger(MarkAll.class.getName()).log(
java.util.logging.Level.SEVERE,null,ex);
}catch(javax.swing.UnsupportedLookAndFeelException ex){
java.util.logging.Logger.getLogger(MarkAll.class.getName()).log(
java.util.logging.Level.SEVERE,null,ex);
}
// 
/*创建并显示表单*/
invokeLater(new Runnable()){
@凌驾
公开募捐{
新的MarkAll().setVisible(true);
}
});
}
Highlighter.HighlightPainter myHighLightPainter=new FindAWord.myHighLightPainter(
颜色:浅灰色);
//变量声明-不修改
私有javax.swing.JScrollPane滚动窗格;
私有javax.swing.JTextField searchText;
私有javax.swing.JTextPane textPane;
私有javax.swing.JButton搜索;
公共FindAWord(){
初始化组件();
}
public void removeHighLights(JTextComponent组件){
Highlighter hilet=component.getHighlighter();
Highlighter.Highlight[]highLites=hilet.getHighlights();
对于(int i=0;i=0){
hLite.addHighlight(pos,pos+patteren.length(),
我的强光画家);
pos+=patteren.length();
}
}捕获(例外e){
}
}
@抑制警告(“未选中”)
// 
私有组件(){
search=newjavax.swing.JButton();
searchText=newjavax.swing.JTextField();
scrollPane=newjavax.swing.JScrollPane();
textPane=newjavax.swing.JTextPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
search.setText(“search”);
search.addActionListener(新java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
执行的搜索操作(evt);
}
});
scrollPane.setViewportView(文本窗格);
javax.swing.GroupLayout布局=新建javax.swing.GroupLayout(
getContentPane());
getContentPane().setLayout(布局);
布局。setHorizontalGroup(布局
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
layout.createSequentialGroup()
.addGap(36,36,36)
.addComponent(搜索,
javax.swing.GroupLayout.PREFERRED_SIZE,
91,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32,32,32)
.addComponent(搜索文本,
javax.swing.GroupLayout.PREFERRED_SIZE,
120,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(114,简称最大值))
.addGroup(
javax.swing.GroupLayout.Alignment.training,
layout.createSequentialGroup().addComponent(滚动窗格)
.addContainerGap());
布局。setVerticalGroup(布局
.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(
layout.createSequentialGroup()
.addGap(36,36,36)
.addGroup(
布局。
import javax.swing.text.*;
import java.awt.*;

public class FindAWord extends javax.swing.JFrame {

    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 (Exception ex) {
            ex.printStackTrace();
        }
        //</editor-fold>

    /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new FindAWord().setVisible(true);
            }
        });
    }
    Highlighter.HighlightPainter myHighLightPainter=new    FindAWord.MyHighightPainter(Color.LIGHT_GRAY);
    // Variables declaration - do not modify
    private javax.swing.JScrollPane scrollPane;
    private javax.swing.JTextField searchText;
    private javax.swing.JTextPane textPane;
    private javax.swing.JButton search;
    public FindAWord() {
        initComponents();
    }
    public void highLight(JTextComponent component,String patteren){
        try {
            Document doc=component.getDocument();
            String text=component.getText(0,doc.getLength());
            int pos=component.getCaretPosition();
            if (pos==doc.getLength()) {
                pos=0;
            }
            int index=text.toUpperCase().indexOf(patteren.toUpperCase(),pos);
            if (index>=0) {
                component.setSelectionStart(index);
                component.setSelectionEnd(index+patteren.length());
                component.getCaret().setSelectionVisible(true);
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
    @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        search = new javax.swing.JButton();
        searchText = new javax.swing.JTextField();
        scrollPane = new javax.swing.JScrollPane();
        textPane = new javax.swing.JTextPane();
        searchText.setText("test");
        textPane.setText("test qweqw test asdasdas test");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        search.setText("Search");
        search.setFocusable(false);
        search.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchActionPerformed(evt);
            }
        });

        scrollPane.setViewportView(textPane);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGap(36, 36, 36)
                                .addComponent(search, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(32, 32, 32)
                                .addComponent(searchText, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap(114, Short.MAX_VALUE))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(scrollPane)
                                .addContainerGap())
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGap(36, 36, 36)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(search)
                                        .addComponent(searchText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(scrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE))
        );

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

    private void searchActionPerformed(java.awt.event.ActionEvent evt) {
        highLight(textPane, searchText.getText());
    }

    class MyHighightPainter extends DefaultHighlighter.DefaultHighlightPainter{
        MyHighightPainter(Color color){
            super(color);
        }
    }
}