setText
就是这样做的,它将字段的文本“设置”为您提供的值,删除所有以前的内容。
你想要的是JTextArea#append http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html#append(java.lang.String)
如果您使用的是 Java 8,另一个选择可能是StringJoiner https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html
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 更新。相反,您需要使用 SwingTimer
例如,定期安排回调并在每次更新时更改 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 中的并发 http://docs.oracle.com/javase/tutorial/uiswing/concurrency/ and 如何使用 Swing 定时器 http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html更多细节