【问题标题】:How to find a exact string but that is not a sub string in JtextPane如何找到一个确切的字符串,但它不是 JtextPane 中的子字符串
【发布时间】:2014-07-02 07:07:11
【问题描述】:

我写了一个查找给定字符串的代码。它是找出给定的单词,它可能是单词的子字符串或单词。但是,我想找到确切的单词而不是那个单词的子字符串。例如 SearchExactword是一个单词,我搜索字符串作为单词。如果单词在文本中可用,它将突出显示但不突出显示单词的子字符串(SearchExactword)。请帮助我,谢谢。

我的代码是:

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);
        }
    });
}
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);
        int start = Utilities.getWordStart(component, index);
        int end = Utilities.getWordEnd(component, index + patteren.length());

        int patterenLn=patteren.length();
        int diff=end-start;
        if (index >= 0) {
            if((start==index)&&(end==index+patterenLn+1)){
            component.setSelectionStart(index);
            component.setSelectionEnd(index + patteren.length());
            component.getCaret().setSelectionVisible(true);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@SuppressWarnings("unchecked")

//
私有 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());
}

}

【问题讨论】:

  • 您可以使用带有PatternMatcher 类的REGEX
  • 首先您应该解释一下您提供的代码哪些有效,哪些无效。
  • 一般建议可能与您当前的问题无关:不惜一切代价避免空的 catch 子句!至少输出一个 sysout 或者更好地创建一个日志条目,否则你甚至不会注意到出现问题...

标签: java string swing awt jtextpane


【解决方案1】:

使用javax.swing.text.Utilities。它有两种方法

public static final int getWordStart(JTextComponent c, int offs)
public static final int getWordEnd(JTextComponent c, int offs)

找到匹配项后,您可以检查找到的单词开头和结尾。如果它与找到的字符串开始和结束偏移量相同,则找到完全匹配(整个单词)

【讨论】:

  • 我修改了代码,请检查一下。谢谢。
  • 我完全理解并在这里写了它是如何实现的。我没有时间编写确切的工作代码,但提供了如何实现它的总体思路。
  • 我已经用一些额外的逻辑编辑了代码。但是,它有时不起作用。请检查一下。谢谢。
  • 您应该比较以索引开头的单词和以索引+搜索字符串长度的单词结尾
  • 我已经修改了逻辑,只有最后一次出现的搜索刺仍然有效。请检查一次。谢谢:if (index >= 0) { if((start ==index)&&(end==index+patterenLn+1)){ component.setSelectionStart(index); component.setSelectionEnd(index + pattern.length());组件.getCaret().setSelectionVisible(true); } }
【解决方案2】:

有很多方法可以做到这一点。只是一个简单的逻辑/想法

String text="Entire text goes here";
String toFind="text";
StringTokenizer st = new StringTokenizer(text);
while(st.hasMoreTokens())
{
if(toFind.equals(st.nextToken())
 {
   System.out.println("Keyword matched");
      return true;
}

}
    return false;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    • 2020-03-12
    相关资源
    最近更新 更多