JTextArea中的Java Swing更新字符串
我的JTextArea中有一个字符串,下面是我的程序的一个简单示例:JTextArea中的Java Swing更新字符串,java,swing,textarea,Java,Swing,Textarea,我的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() =
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。我的问题是如何更新我的textarea以反映这一变化,因为更多的文本已附加到textarea,因此不能简单地删除
。我的问题是如何更新我的textarea以反映这一变化,因为更多的文本已附加到textarea,因此不能简单地删除
然后,您需要在添加文本时跟踪“价格值”的偏移量
然后,当您想要重置该值时,您可以重置该文本。可能是这样的:
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);
或者另一种方法是删除第一行,然后将其添加回文档中。比如:
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);
简单性建议将文本移到文本字段而不是标题,这实际上取决于文本区域中的内容,而不是价格。如果它是一个固定的、不太复杂的模板,那么您可以将其保存在适合
String.format
的格式中,每次只需将String.format
与新价格一起使用即可。如果是动态的,我们需要更多的信息。这不是一个好主意,你想做什么