【问题标题】:Java Swing Updating String in a JTextAreaJTextArea 中的 Java Swing 更新字符串
【发布时间】:2014-12-20 18:47:12
【问题描述】:

所以我的 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。我的问题是如何更新我的 textarea 以反映此更改,因为更多文本已附加到 textarea,因此不能简单地删除它。

【问题讨论】:

  • 简单建议将文本移动到文本字段
  • 这实际上取决于文本区域中的内容,而不是您的价格。如果它是一个固定的、不太复杂的模板,您可以将其保存在适合String.format 的格式中,并且每次只需使用带有新价格的String.format。如果它是动态的,我们将需要更多信息。
  • 你想要做什么真的不是一个好主意

标签: java swing textarea


【解决方案1】:

。我的问题是如何更新我的 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-03
    • 2017-07-30
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-08
    相关资源
    最近更新 更多