我已经制作了自己的SwingWorker示例,以熟悉它的工作原理.
我想要做的是以下内容:当单击按钮时,我想要一个进度条出现,直到任务完成我想简单地删除进度条并在对话框中添加一个字符串.
单击该按钮时,进度条会出现,但永远不会消失.(10秒后永远不会删除进度条,永远不会放置标签)
这是一个SSCCE:
package swingtesting;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
public class SwingTesting {
/**
* Creates a frame that will hold a simple button to make use of SwingWorker
*/
public static void main(String[] args) {
// TODO code application logic here
JFrame frame = new JFrame();
JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new GuiWorker().execute();
}
});
button.setText("Test Me");
frame.getContentPane().add(button); …Run Code Online (Sandbox Code Playgroud) 我正在为我的设计使用MVC模式,当用户按下搜索按钮时,我在模型中调用搜索,但我还想更新从该模型返回的信息的进度条.
我尝试过使用swingworker,但进度条没有更新.我怀疑我的线程出错了.
我在控制器中定义的按钮是:
class SearchBtnListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
_view.displayProgress();
}
}
Run Code Online (Sandbox Code Playgroud)
这将调用模型中的搜索,并在视图中进行以下调用:
public void displayProgress() {
TwoWorker task = new TwoWorker();
task.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
if ("progress".equals(e.getPropertyName())) {
_progressBar.setValue((Integer) e.getNewValue());
}
}
});
task.execute();
}
private class TwoWorker extends SwingWorker<Void, Void> {
@Override
protected Void doInBackground() throws Exception {
_model.startSearch(getTerm()); // time intensive code
File file = new File("lock");
while (file.exists()){
setProgress(_model.getStatus());
System.out.println(_model.getStatus()); // never called
}
return null;
} …Run Code Online (Sandbox Code Playgroud) 我正在尝试学习如何使用Java的executorservice,
我正在阅读以下讨论Java线程的简单队列
在这里有一个示例
ExecutorService service = Executors.newFixedThreadPool(10);
// now submit our jobs
service.submit(new Runnable() {
public void run() {
do_some_work();
}
});
// you can submit any number of jobs and the 10 threads will work on them
// in order
...
// when no more to submit, call shutdown
service.shutdown();
// now wait for the jobs to finish
service.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
Run Code Online (Sandbox Code Playgroud)
我尝试实现这个解决方案,为此我创建了一个表单并放置了启动和停止按钮,但我遇到的问题是,如果我在启动按钮上调用此过程,它将挂起完整的表单,我们需要等到所有进程完成了.
我还尝试阅读以下https://www3.ntu.edu.sg/home/ehchua/programming/java/J5e_multithreading.html
但到目前为止,我无法理解如何使其工作,因为点击开始按钮后,我应该获得访问权限,假设我想要停止该过程.
有人可以指导我正确的方向.
谢谢
为了使我的情况更清楚,我正在添加我正在测试的代码.
问题
1)程序执行时,完整表格保持冻结状态.2)进度条不起作用,只有在所有过程完成后才会显示状态.
private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {
TestConneciton();
}
private void …Run Code Online (Sandbox Code Playgroud)