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).
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. Is that possible somehow? I tried repaint() but that did not do the trick. 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.
you should not call txtBasket.getText() in the loop since you'll get the previous text each time.
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:
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);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.