Java如何替换JTextArea中的文本?
在此示例中,您将看到如何使用replaceRange(Stringstr,intstart,intend)方法JTextArea将start位置中的字符串替换为end指定字符串中的位置。
package org.nhooo.example.swing;
import javax.swing.*;
import java.awt.*;
public class TextAreaReplaceText extends JPanel {
public TextAreaReplaceText() {
initializeUI();
}
private void initializeUI() {
String text = "The quick white fox jumps over the sleepy dog.";
JTextArea textArea = new JTextArea(text);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(textArea);
textArea.replaceRange("brown", 10, 15);
textArea.replaceRange("lazy", 35, 41);
this.setPreferredSize(new Dimension(500, 200));
this.setLayout(new BorderLayout());
this.add(scrollPane, BorderLayout.CENTER);
}
public static void showFrame() {
JPanel panel = new TextAreaReplaceText();
panel.setOpaque(true);
JFrame frame = new JFrame("JTextArea Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TextAreaReplaceText.showFrame();
}
});
}
}上面的代码片段的屏幕截图是:
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短