开发者

JTextPane removing first line

I get Document object from JTextPane, which contains method remove, but specific number of chars textP开发者_运维问答ane.getDocument().remove(begin,end). I would like to remove whole first line.


See Limit Lines in Document. The code in that class will show you how to get the start/end offsets of the characters in the line.

Or you can use the Utilities class.

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

Once you know the start/end you can use the remove() method.


The following shows how to remove the first line (Element) of a JTextPane if you are considering lines "things that end in a newline". If you have fancier content in your Document, you may need to do something more elaborate

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());


How are you creating the String that goes in the first line? If the code telling the JTextPane what string to write is based off an existing String variable like below

private String myString = "Hello, this is the first line!";
private JTextPane myPane = new JTextPane(...);
...
public void writeFirstLine(){
 myPane.setText(myString); 
}

then you can do the following:

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

if you don't have the first line pre-defined as above and you basically just want to remove up to the first period or other special character, you can use a StreamTokenizer to find the target separating character (which can be the end of a line [EOL] with EOL set to significant. You can set whitespace to significant in a streamtokenizer and add them as soon as they are encountered to a character counter variable. Then you would essentially cast each token to string inside an initially null String object (that you re-use for each token) before allowing the streamtokenizer to move on and obtain the character length of each, adding it to the character counter variable before moving on to the next token. When the separator punctuation character is reached, run the addition operation once more for the last token, and then your character counter variable will have the number of characters up to the end of the first line. In this case, the code would be:

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

hope this helps CCJ

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜