簡體   English   中英

JTextArea中的Java Swing更新字符串

[英]Java Swing Updating String in a JTextArea

所以我的JTextArea中有一個String,這是我的程序的一個簡單示例:

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。 我的問題是我將如何更新文本區域以反映此更改,因為進一步的文本已添加到文本區域,因此不能簡單地將其刪除。

我的問題是我將如何更新文本區域以反映此更改,因為進一步的文本已添加到文本區域,因此不能簡單地將其刪除。

然后,在添加文本時,您需要跟蹤“價格值”的偏移量。

然后,當您想重置該值時,您只需重置該文本即可。 也許像這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM