[英]Clearing JTextArea, set new text
So I have this snippet of a software piece I'm writing. 因此,我有正在编写的软件片段。
Currently, this snippet outputs all the items I have in my ArrayList (cart). 当前,此代码段输出我在ArrayList(购物车)中拥有的所有项目。
JButton btnShowCart = new JButton("Show cart");
btnShowCart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
for (int i = 0; i < listWithItems.size(); i++) {
txtBasket.setText(txtBasket.getText() + listWithItems.get(i) + "\n" );
}
}
});
Whenever I click "show cart", I see what my list contains. 每当我单击“显示购物车”时,我就会看到列表中包含的内容。 That's perfect but I want it to clear the text before the JTextArea sets the text again from my ArrayList, otherwise I see the old text as well.
完美,但是我希望它在JTextArea再次从ArrayList设置文本之前清除文本,否则我也看到旧文本。 Is that possible somehow?
有可能吗? I tried repaint() but that did not do the trick.
我尝试了repaint(),但是没有成功。 I also tried setText(""), but that just made me unable to show any text at all, even though I've tried putting the setText("") before/after I set the text from using my arraylist.
我也尝试过setText(“”),但这使我根本无法显示任何文本,即使我尝试在使用arraylist设置文本之前/之后放置setText(“”)。
you should not call txtBasket.getText() in the loop since you'll get the previous text each time. 您不应在循环中调用txtBasket.getText(),因为您每次都会获得前一个文本。
try something like this : 尝试这样的事情:
JButton btnShowCart = new JButton("Show cart");
btnShowCart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String content = "";
for (int i = 0; i < listWithItems.size(); i++) {
content += listWithItems.get(i) + "\n" ;
}
txtBasket.setText(content);
}
});
If this is JAVA/SWING, maybe you need to call SwingUtilities like this: 如果这是JAVA / SWING,则可能需要像这样调用SwingUtilities:
String text = "";
for (int i = 0; i < listWithItems.size(); i++) {
text += txtBasket.getText() + listWithItems.get(i) + "\n";
}
// update GUI
SwingUtilities.invokeLater(new Runnable() {
public void run() {
statusLabel.setText(text);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.