0
我遇到一個奇怪的問題。
這種情況是我需要用另一個詞替換JTextArea
中的關鍵字。
我有兩個按鈕,一個是找到關鍵字,另一個是替換關鍵字。
對於這兩個按鈕,我添加鼠標偵聽器並實現函數mouseClicked
。在當前階段,我可以突出顯示找到的關鍵字並滾動到關鍵字位置。但是在處理替換按鈕時,在重新設置文本後,JTextArea
總是向下滾動到底部,但我想保持替換髮生的位置,我該怎麼辦?以下是我的代碼片段,但它不起作用。JTextArea在重新設置文本後不要scrollRectToVisible
replaceBtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
String keyword = jKeyword.getText();
if (keyword.length() == 0)
return;
String text = jTextArea.getText();
pos = text.indexOf(keyword, 0);
if (pos == -1) {
pos = 0;
JOptionPane.showMessageDialog(null, "can not find " + keyword);
return;
}
jTextArea.setText(text.replaceFirst(keyword, jReplaceKW.getText()));
//jTextArea.revalidate();
//scroll to first keyword occurrence
try {
Rectangle rectangle = jTextArea.modelToView(pos);
jTextArea.scrollRectToVisible(rectangle);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
}
});