Java 程序替换 JTextArea 中的前 10 个字符
java 8object oriented programmingprogramming更新于 2025/9/1 18:20:17
要替换文本区域中的前 10 个字符,请使用 Java 中的 replaceRange() 方法,将旧文本替换为新文本。
假设以下是使用 JTextArea 减号设置的演示文本
JTextArea textArea = new JTextArea("这是示例中显示的文本。我们替换了部分文本。");
现在,替换指定范围内的字符 "
int begn = 0;
int end = 10;
// 替换
textArea.replaceRange("Replaced! ", begn, end);
以下示例替换 JTextArea 中的前 10 个字符 −
示例
package my;
import java.awt.GridLayout;
import javax.swing.*;
public class SwingDemo {
SwingDemo() {
JFrame frame = new JFrame("Demo");
JTextArea textArea = new JTextArea("This is a text displayed for our example. We have replaced some of the text.");
int begn = 0;
int end = 10;
// replace
textArea.replaceRange("Replaced! ", begn, end);
frame.add(textArea);
frame.setSize(550,300);
frame.setLayout(new GridLayout(2, 2));
frame.setVisible(true);
}
public static void main(String args[]) {
new SwingDemo ();
}
}
输出


