setText做到这一点,它将“字段的文本”设置为您提供的值,从而删除所有先前的内容。
你想要的是
Jtextarea#append
如果您使用的是Java 8,则另一个选择可能是
StringJoiner
StringJoiner joiner = new StringJoiner(", ");for (int i = 0; i < 10; i++) { joiner.add("QUang " + i);}jtextarea1.setTexy(joiner.toString());(假设您想在每次
actionPerformed调用该方法时替换文本,但仍然可以使用
append)
根据评论的假设进行更新
我“假设”您的意思是您希望每个元素都
String显示一小段时间,然后替换为下一个
String。
Swing是一个单线程环境,因此任何阻塞事件分派线程的事件(例如循环)都将阻止UI的更新。相反,您需要使用Swing
Timer定期安排回调,并在每个刻度上更改UI。
import java.awt.BorderLayout;import java.awt.EventQueue;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.Jframe;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.Jtextarea;import javax.swing.Timer;import javax.swing.UIManager;import javax.swing.UnsupportedLookAndFeelException;public class Test { public static void main(String[] args) { new Test(); } public Test() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } Jframe frame = new Jframe("Testing"); frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); frame.add(new TestPane()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class TestPane extends JPanel { private String[] messages = { "Example 1", "Example 2", "Example 3", "Example 4", "Example 5", "Example 6", "Example 7", "Example 8", "Example 9", }; private Jtextarea ta; private int index; private Timer timer; public TestPane() { setLayout(new BorderLayout()); ta = new Jtextarea(1, 20); add(new JScrollPane(ta)); JButton btn = new JButton("Start"); btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (timer.isRunning()) { timer.stop(); } index = 0; timer.start(); } }); add(btn, BorderLayout.SOUTH); timer = new Timer(500, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (index < messages.length) { ta.setText(messages[index]); } else { timer.stop(); } index++; } }); } }}了解Swing中的并发性以及如何使用Swing计时器以了解更多详细信息



