Reputation:
So I have a String in my JTextArea, here is a simple example of my program:
int price = 0;
String totalPrice = "Total price is:" + price;
JTextArea outputText = new JTextArea(totalPrice);
outputText.append("\n New Item");
public void actionPerformed(ActionEvent e) {
if(e.getSource() == addPriceButton) {
price += 1;
}
}
The price variable is increased by 1 every time a button is pressed. My question is how would I update my textarea to reflect this change, as further text has been appended to the textarea so it can not simply be erased.
Upvotes: 0
Views: 234
Reputation: 324197
. My question is how would I update my textarea to reflect this change, as further text has been appended to the textarea so it can not simply be erased.
Then you need to keep track of the offset of the "price value" when you add the text.
Then when you want to reset the value you can just reset that piece of text. Maybe something like:
JTextArea outputText = new JTextArea(totalPrice);
int offset = outputText.getDocument.getLength() - 1;
...
price++;
outputText.replaceRange("" + price, offset, offset + 1);
Or another approach is to remove the first line and then add it back into the document. Something like:
Document doc = outputText.getDocument();
int start = outputText.getLineStartOffset();
int end = outputText.getLineEndOffset();
doc.remove(start, end - start);
doc.insertString(0, "your new text here", null);
Upvotes: 1