Java JTextPane正在删除第一行

Java JTextPane正在删除第一行,java,swing,jtextpane,Java,Swing,Jtextpane,我从JTextPane获取Document对象,该对象包含方法remove,但包含特定数量的字符textPane.getDocument()。remove(begin,end)。我想删除整个第一行。请参阅。该类中的代码将向您展示如何获取行中字符的开始/结束偏移量 或者您可以使用Utilities类 getRowStart(...) getRowEnd(...); 一旦知道了开始/结束,就可以使用remove()方法。如何创建第一行中的字符串?如果告诉JTextPane要写入哪个字符串的代码是基

我从
JTextPane
获取
Document
对象,该对象包含方法
remove
,但包含特定数量的字符
textPane.getDocument()。remove(begin,end)
。我想删除整个第一行。

请参阅。该类中的代码将向您展示如何获取行中字符的开始/结束偏移量

或者您可以使用Utilities类

getRowStart(...)
getRowEnd(...);

一旦知道了开始/结束,就可以使用remove()方法。

如何创建第一行中的字符串?如果告诉JTextPane要写入哪个字符串的代码是基于一个现有的字符串变量的,如下所示

private String myString = "Hello, this is the first line!";
private JTextPane myPane = new JTextPane(...);
...
public void writeFirstLine(){
 myPane.setText(myString); 
}
然后您可以执行以下操作:

textPane.getDocument().remove(0, myString.length()); //this is assuming the remove function 
//excludes the end index and removes everything up to it.  Otherwise, it would be  
//myString.length()-1
如果没有如上所述预定义的第一行,并且基本上只想删除第一个句点或其他特殊字符,则可以使用查找目标分隔字符(可以是行[EOL]的结尾)将EOL设置为有效。您可以在streamtokenizer中将空白设置为有效,并在遇到字符计数器变量时立即将其添加到字符计数器变量中。然后,您可以将每个标记强制转换为初始为空的字符串对象内的字符串(对于每个标记重复使用)在允许streamtokenizer继续并获取每个标记的字符长度之前,请先将其添加到字符计数器变量,然后再移动到下一个标记。当达到分隔符标点字符时,再次对最后一个标记运行添加操作,然后您的字符计数器变量将具有字符数直到第一行末尾。在这种情况下,代码为:

textPane.getDocument().remove(0,charCounter) //this is assuming the remove function 
//excludes the end index and removes everything up to it.  Otherwise, it would be charCounter-1
希望这有帮助
CCJ

如果您正在考虑行“以换行结尾的内容”,则以下说明如何删除JTextPane的第一行(元素)。如果您的文档中有更丰富的内容,您可能需要做一些更详细的操作

JTextPane pane = new JTextPane();
pane.setText("I've got to go\nI can stay, though.\nThree lines of text?");
System.out.println(pane.getText());

System.out.println("\n\n\n removing! \n\n\n");
Element root = pane.getDocument().getDefaultRootElement();
Element first = root.getElement(0);
pane.getDocument().remove(first.getStartOffset(), first.getEndOffset());
System.out.println(pane.getText());

第一行中有多少个字符?数一数,然后删除它们。我想了一下,但我不知道howcamickr的答案比我的答案简单得多;先探索一下。我已经有一段时间没有使用SWING组件了:)链接有完美的源代码,完全满足了需要!