我有一个有趣的项目,我需要在迭代中更改文本区域的内容。
它是一个角色,一个“射弹”,移动着一根绳子。字符串被更新并发送到迭代内的textArea,当字符到达墙时迭代停止。
但是当我离开迭代时,我的textArea仅在视觉上更新。当我在其中时,textArea会冻结,就像它等待迭代一样,即使它内部有Thread.sleep()。
我制作了一个MVCE例证下面的问题,注意文本只在迭代后显示,我希望它能在每一步中显示出来。
public class GUIProblem extends JFrame{
public GUIProblem() {
setSize(640, 480);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
final JTextArea textArea = new JTextArea();
textArea.setRows(10);
textArea.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
int i = 0;
while(i < 10){
textArea.setText("this text only appears after the iteration, i want it to appear in each step of the iteration!");
System.out.println("iterating..." + i++);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
textArea.setColumns(30);
panel.add(textArea);
}
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
GUIProblem gui = new GUIProblem( );
gui.setVisible(true);
}
});
JOptionPane.showMessageDialog(null, "Click the textArea!");
}
}
答案 0 :(得分:4)
您有一个经典的Swing线程问题,您可以使用迭代及其Thread.sleep()
调用停止其轨道中的Swing事件线程。解决方案与类似问题的解决方案相同:使用Swing Timer或后台线程(如SwingWorker)。在您的情况下,请使用计时器。
例如,因为您发布了MCVE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUIProblem extends JFrame {
public GUIProblem() {
// setSize(640, 480);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
final JTextArea textArea = new JTextArea(20, 50);
textArea.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent mEvt) {
int i = 0;
int timerDelay = 200;
new Timer(timerDelay, new ActionListener() {
int count = 0;
private final int MAX_COUNT = 10;
@Override
public void actionPerformed(ActionEvent e) {
if (count >= MAX_COUNT) {
((Timer) e.getSource()).stop(); // stop the timer
return;
}
textArea.append("Count is: " + count + "\n");
count++;
}
}).start();
}
});
panel.add(new JScrollPane(textArea));
}
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
GUIProblem gui = new GUIProblem();
gui.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
gui.pack();
gui.setLocationRelativeTo(null);
gui.setVisible(true);
}
});
JOptionPane.showMessageDialog(null, "Click the textArea!");
}
}