所以我的 JTextArea 中有一个字符串,这是我的程序的一个简单示例:
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;
}
}
每次按下按钮,价格变量都会增加 1。我的问题是如何更新我的文本区域以反射(reflect)此更改,因为更多文本已附加到文本区域,因此不能简单地删除它。
最佳答案
. 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.
然后,您需要在添加文本时跟踪“价格值”的偏移量。
然后,当您想重置该值时,只需重置该文本即可。也许是这样的:
JTextArea outputText = new JTextArea(totalPrice);
int offset = outputText.getDocument.getLength() - 1;
...
price++;
outputText.replaceRange("" + price, offset, offset + 1);
或者另一种方法是删除第一行,然后将其添加回文档中。像这样的东西:
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);
关于Java Swing 更新 JTextArea 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26556240/