【发布时间】:2020-07-12 12:26:27
【问题描述】:
嘿,下面的所有代码都适用于突出显示要搜索的提供的单词,但如果句子中的单词不止一 (1) 个,则它不会找到它。它只会在找到一 (1) 个匹配项时停止。
private JFrame frame;
private static JTextField textField;
private static JTextField txtWorld;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CaretDemo window = new CaretDemo();
window.frame.setVisible(true);
String text = "hello world. How are you?";
textField.setText(text);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public CaretDemo() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(21, 11, 350, 36);
frame.getContentPane().add(textField);
textField.setColumns(10);
txtWorld = new JTextField();
txtWorld.setColumns(10);
txtWorld.setBounds(21, 156, 350, 36);
frame.getContentPane().add(txtWorld);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Highlighter highlighter = textField.getHighlighter();
HighlightPainter painter = new DefaultHighlighter.DefaultHighlightPainter(Color.pink);
int p0 = textField.getText().indexOf(txtWorld.getText());
int p1 = p0 + txtWorld.getText().length();
try {
highlighter.removeAllHighlights();
highlighter.addHighlight(p0, p1, painter);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
});
btnNewButton.setBounds(221, 203, 128, 29);
frame.getContentPane().add(btnNewButton);
}
上面的代码在运行并提供单词“world”进行查找时看起来像这样。
但是现在如果我添加到句子中并添加另一个“世界”然后点击按钮,这就是它的样子:
如您所见,它仍然有相同的突出显示的单词,但没有同时突出显示第二 (2) 个“世界”。
更新 1
我尝试使用正则表达式来循环查找所需的单词。
btnNewButton_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("hi");
String theSentence = txtTheSentence.getText();
String WordToFind = txtWordToFind.getText();
Highlighter h = txtWordToFind.getHighlighter();
Pattern pattern = Pattern.compile("\\b"+WordToFind+"\\b", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(theSentence);
if(matcher.find()){
String extractedWord = matcher.group(0);
System.out.println(extractedWord);
}
}
});
但这并没有找到一个单词。
【问题讨论】:
-
交叉发布:coderanch.com/t/728672/java/…。给出了同样的建议。
标签: java eclipse swing jtextfield jtextarea