【发布时间】:2014-11-14 14:43:15
【问题描述】:
我正在尝试随机生成一个字符串并不断更新一个 JTextArea。我知道程序在无限循环中挂断在 runTest() 方法中。我试图循环并显示这个结果,直到用户点击停止按钮。有什么建议吗?谢谢
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class MyApplication extends JFrame {
private JTextArea textArea;
private JButton b;
private String toChange = "";
// Called from non-UI thread
private void runQueries() {
while (true) {
runTest();
updateProgress();
}
}
public void runTest() {
while (true) {
if (toChange.length() > 10) {
toChange = "";
}
Random rand = new Random();
toChange += rand.nextInt(10);
}
}
private void updateProgress() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(toChange);
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyApplication app = new MyApplication();
app.setVisible(true);
}
});
}
private MyApplication() {
this.setLayout(null);
this.setResizable(false);
this.setLocation(100, 100);
this.setSize(900, 600);
final Panel controlPanel = new Panel();
controlPanel.setLayout(new BorderLayout());
controlPanel.setSize(600, 200);
controlPanel.setLocation(50, 50);
setDefaultCloseOperation(this.EXIT_ON_CLOSE);
textArea = new JTextArea("test");
textArea.setSize(100, 100);
textArea.setLocation(200, 200);
this.add(textArea);
JButton b = new JButton("Run query");
b.setSize(100, 75);
b.setLocation(100, 50);
this.add(b);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread queryThread = new Thread() {
public void run() {
runQueries();
}
};
queryThread.start();
}
});
}
}
【问题讨论】:
-
我认为您希望在新线程上执行重复任务。给我一分钟来获取代码。
-
将
Thread queryThread设为class 变量并在“停止”按钮的actionPerformed()方法中执行queryThread.interrupt()。请参阅Java Thread Primitive Deprecation 了解更多信息。 -
Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。
-
参见here 显示的示例。希望如果您阅读了整个主题,您会学到很多关于 Swing 并发的知识。同样可以启动和停止的 Swing Timer 也可以用作 SwingWorker 的替代品。
标签: java multithreading swing jtextarea