如何取消突出显示JTextPane中的文本

时间:2014-07-01 06:45:11

标签: java swing jtextpane

我已经编写了一个代码来查找JTextPane中的单词。这里的问题是,当我输入搜索词并单击搜索按钮时,它突出显示给定搜索词的所有出现。我想突出显示该单词的第一个出现,然后单击搜索按钮显示第二次出现的方式。另一个是当点击文本窗格时,不是unHighlight搜索完成后。

我的代码:

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

1 个答案:

答案 0 :(得分:3)

如果您只需突出显示一个字词,则不需要addHighlight()removeHighlight()所有来电。

找出单词的偏移量(和长度),并使用setSelectionStart()/setSelectionEnd()的{​​{1}}方法传递单词start和start + length

按要求更新工作代码

JTextPane