gpt4 book ai didi

java - 荧光笔突出显示所有文本区域而不是特定单词及其出现次数 [java]

转载 作者:行者123 更新时间:2023-12-01 10:06:49 25 4
gpt4 key购买 nike

我在 textArea 中使用荧光笔类时遇到一些问题。我的程序应该像这样工作:

在文本区域中,程序检测到应放置在第一行的字符串(不考虑用“#”标记的注释行),突出显示该字符串及其在整个文本区域中出现的所有内容。

示例:

#this is an example code
#these line are comments
**whateverWordIsFine** #this is the word to highlight
//code
//code
**whateverWordIsFine** #occurrence to be highlighted
//
//
**whateverWordIsFine** #occurrence to be highlighted

我的代码只是突出显示所有文本区域。这是我的代码。

import java.awt.Color;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;



public class NewJFrame extends javax.swing.JFrame {

/**
* Creates new form NewJFrame
*/
public NewJFrame() throws BadLocationException {
initComponents();

textArea.getDocument().addDocumentListener(new DocumentListener() {
String keyWord = findKeyWord();
@Override
public void insertUpdate(DocumentEvent e) {
try {
findOccurrences();
} catch (BadLocationException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}

@Override
public void removeUpdate(DocumentEvent e) {
try {
findOccurrences();
} catch (BadLocationException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}

@Override
public void changedUpdate(DocumentEvent e) {
try {
findOccurrences();
} catch (BadLocationException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}

public String findKeyWord() throws BadLocationException {
if (textArea.getText().isEmpty())
return "";

String keyWord = "";

for( String line : textArea.getText().split("\n")){
if( !line.startsWith("#") ){
int keywordEndPosition = line.indexOf("#");
keyWord = line.substring(0, keywordEndPosition == -1 ? line.length() : keywordEndPosition);
keyWord = keyWord.trim();
break;
}
}

return keyWord;

}

public void findOccurrences() throws BadLocationException {
Highlighter highlighter = textArea.getHighlighter();
DefaultHighlighter.DefaultHighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.CYAN);

highlighter.removeAllHighlights();

if (keyWord.isEmpty())
return;
Pattern pattern = Pattern.compile( Pattern.quote(keyWord) );
Matcher matcher = pattern.matcher(textArea.getText());

while(matcher.find()) {
highlighter.addHighlight(matcher.start(), matcher.end(), painter);
}

}


});


}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
textArea = new javax.swing.JTextArea();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

textArea.setColumns(20);
textArea.setRows(5);
jScrollPane1.setViewportView(textArea);

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 417, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE)
);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);

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

/**
* @param args the command line arguments
*/
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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new NewJFrame().setVisible(true);
} catch (BadLocationException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}

}
});
}
// Variables declaration - do not modify
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea textArea;
// End of variables declaration
}

最佳答案

不确定我是否完全理解您希望程序如何工作,但我是这样解释的:

不以#开头的第一行包含一个关键字,并且该关键字应在整个文本中突出显示。

这不必像您当前拥有的代码那么复杂。您只需找到关键字,然后找到所有出现的关键字并突出显示它们。

public String findKeyWord() throws BadLocationException {
if( textArea.getText().isEmpty() )
return "";

String keyWord = "";
for( String line : textArea.getText().split("\n")){
if( !line.startsWith("#") ){
int keywordEndPosition = line.indexOf("#");
keyWord = line.substring(0, keywordEndPosition == -1 ? line.length() : keywordEndPosition );
keyWord = keyWord.trim();
break;
}
}

return keyWord;
}

 

public void findOccurrences() throws BadLocationException {  
Highlighter highlighter = textArea.getHighlighter();
DefaultHighlighter.DefaultHighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.CYAN);

highlighter.removeAllHighlights();

if( keyWord.isEmpty() )
return;

Pattern pattern = Pattern.compile( Pattern.quote(keyWord) );
Matcher matcher = pattern.matcher(textArea.getText());

while(matcher.find()) {
highlighter.addHighlight(matcher.start(), matcher.end(), painter);
}
}

然后你必须改变

findKeyWord();

在所有监听器函数中

keyWord = findKeyWord();

关于java - 荧光笔突出显示所有文本区域而不是特定单词及其出现次数 [java],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36384683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com