Java SwingWorker未从进程内部更新progressbar
我有一个Java8Swing应用程序,当用户单击一个新按钮时,需要添加一个耗时的操作。我认为这是一个完美的SwingWorker用例,尽管我以前从未写过。完整的源代码和 当用户单击按钮时,应用程序必须从几个不同的来源收集信息,然后启动此后台操作。它将计算一个Java SwingWorker未从进程内部更新progressbar,java,swing,swingworker,edt,Java,Swing,Swingworker,Edt,我有一个Java8Swing应用程序,当用户单击一个新按钮时,需要添加一个耗时的操作。我认为这是一个完美的SwingWorker用例,尽管我以前从未写过。完整的源代码和 当用户单击按钮时,应用程序必须从几个不同的来源收集信息,然后启动此后台操作。它将计算一个inputalysis,然后将该inputalysis返回到EDT中的单击处理程序以更新UI。当它工作时,我希望它也能更新一个JProgressBar,以便用户看到正在取得的进展。我迄今为止最好的尝试是: package com.exampl
inputalysis
,然后将该inputalysis
返回到EDT中的单击处理程序以更新UI。当它工作时,我希望它也能更新一个JProgressBar
,以便用户看到正在取得的进展。我迄今为止最好的尝试是:
package com.example.swingworker.suchwow;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.util.List;
public class MegaApp {
public static void main(String[] args) {
new MegaApp().run();
}
public void run() {
SwingUtilities.invokeLater(() -> {
System.out.println("starting app");
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame mainWindow = new JFrame("Some Simple App!");
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setResizable(true);
mainWindow.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.out.println("app is shutting down");
System.exit(0);
}
});
JPanel jPanel = new JPanel();
JTextField superSecretInfoTextField = new JTextField();
JButton analyzeButton = new JButton("Analyze");
JProgressBar progressBar = new JProgressBar();
superSecretInfoTextField.setPreferredSize(new Dimension(200,
(int)superSecretInfoTextField.getPreferredSize().getHeight()));
jPanel.add(superSecretInfoTextField);
jPanel.add(analyzeButton);
jPanel.add(progressBar);
progressBar.setValue(0);
analyzeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// on click, scoop some info from the input and run a time-consuming task.
// usually takes 20 - 30 seconds to run, and I'd like to be updating the progress
// bar during that time.
//
// also need to handle cases where the task encounters a POSSIBLE error and needs to
// communicate back to the EDT to display a JOPtionPane to the user; and then get the
// user's response back and handle it.
//
// also need to handle the case where the long running task encounters both a checked
// and unchecked/unexpected exception
String superSecretInfo = superSecretInfoTextField.getText();
// here is where we start the long-running task. ideally this needs to go into a SwingWorker
// however there is a somewhat complex back-and-forth-communication required. see the analysis
// method comments for details
try {
InputAnalysis analysis = analysisService_analyze(progressBar, superSecretInfo, mainWindow);
superSecretInfoTextField.setText(analysis.getSuperSecretAnswer());
} catch (IOException ex) {
System.out.println(ex.getMessage());
JOptionPane.showMessageDialog(
mainWindow,
"Something went wrong",
"Aborted!",
JOptionPane.WARNING_MESSAGE);
}
// comment the above try-catch out and uncomment all the worker code below to switch over
// to the async/non-blocking worker based method
// MegaWorker analysisWorker = new MegaWorker(mainWindow, progressBar, superSecretInfo);
// analysisWorker.addPropertyChangeListener(evt -> {
//
// if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
// try {
// // this is called on the EDT
// InputAnalysis asyncAnalysis = analysisWorker.get();
// superSecretInfoTextField.setText(asyncAnalysis.getSuperSecretAnswer());
//
// } catch (Exception ex) {
// System.out.println(ex.getMessage());
// }
// }
//
// });
//
// analysisWorker.execute();
}
});
mainWindow.add(jPanel);
mainWindow.pack();
mainWindow.setLocationRelativeTo(null);
mainWindow.setVisible(true);
System.out.println("application started");
});
}
public InputAnalysis analysisService_analyze(JProgressBar progressBar,
String superSecretInfo,
JFrame mainWindow) throws IOException {
progressBar.setValue(25);
// simulate a few seconds of processing
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
throw new RuntimeException("SOMETHIN BLEW UP");
}
// now we are ready to analyze the input which itself can take 10 - 15 seconds but
// we'll mock it up here
if (superSecretInfo == null || superSecretInfo.isEmpty()) {
// if the input is null/empty, we'll consider that a "checked exception"; something the
// REAL code I'm using explicitly has a try-catch for because the libraries I'm using throw
// them
throw new IOException("ERMERGERD");
} else if (superSecretInfo.equals("WELL_WELL_WELL")) {
// here we'll consider this an unchecked exception
throw new RuntimeException("DID NOT SEE THIS ONE COMING");
}
progressBar.setValue(55);
// check to see if the input equals "KEY MASTER"; if it does we need to go back to the EDT
// and prompt the user with a JOptionPane
if (superSecretInfo.equalsIgnoreCase("KEY MASTER")) {
int answer = JOptionPane.showConfirmDialog(
mainWindow,
"We have identified a KEY MASTER scenario. Do you wish to proceed?",
"Do you wish to proceed",
JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.NO_OPTION) {
// return a partial InputAnalysis and return
Boolean isFizz = Boolean.TRUE;
String superSecretAnswer = "HERE IS A PARTIAL ANSWER";
Integer numDingers = 5;
return new InputAnalysis(isFizz, superSecretAnswer, numDingers);
}
}
// if we get here, either KEY MASTER was not in the input or they chose to proceed anyway
Boolean isFizz = superSecretInfo.length() < 5 ? Boolean.TRUE : Boolean.FALSE;
String superSecretAnswer = "HERE IS A FULL ANSWER";
Integer numDingers = 15;
progressBar.setValue(100);
return new InputAnalysis(isFizz, superSecretAnswer, numDingers);
}
public class InputAnalysis {
private Boolean isFizz;
private String superSecretAnswer;
private Integer numDingers;
public InputAnalysis(Boolean isFizz, String superSecretAnswer, Integer numDingers) {
this.isFizz = isFizz;
this.superSecretAnswer = superSecretAnswer;
this.numDingers = numDingers;
}
public Boolean getFizz() {
return isFizz;
}
public void setFizz(Boolean fizz) {
isFizz = fizz;
}
public String getSuperSecretAnswer() {
return superSecretAnswer;
}
public void setSuperSecretAnswer(String superSecretAnswer) {
this.superSecretAnswer = superSecretAnswer;
}
public Integer getNumDingers() {
return numDingers;
}
public void setNumDingers(Integer numDingers) {
this.numDingers = numDingers;
}
}
public class MegaWorker extends SwingWorker<InputAnalysis,Integer> {
private JFrame mainWindow;
private JProgressBar progressBar;
private String superSecretInfo;
public MegaWorker(JFrame mainWindow, JProgressBar progressBar, String superSecretInfo) {
this.mainWindow = mainWindow;
this.progressBar = progressBar;
this.superSecretInfo = superSecretInfo;
}
@Override
protected void process(List<Integer> chunks) {
progressBar.setValue(chunks.size() - 1);
}
@Override
protected InputAnalysis doInBackground() throws Exception {
publish(25);
// simulate a few seconds of processing
try {
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
throw new RuntimeException("SOMETHIN BLEW UP");
}
// now we are ready to analyze the input which itself can take 10 - 15 seconds but
// we'll mock it up here
if (superSecretInfo == null || superSecretInfo.isEmpty()) {
// if the input is null/empty, we'll consider that a "checked exception"; something the
// REAL code I'm using explicitly has a try-catch for because the libraries I'm using throw
// them
throw new IOException("ERMERGERD");
} else if (superSecretInfo.equals("WELL_WELL_WELL")) {
// here we'll consider this an unchecked exception
throw new RuntimeException("DID NOT SEE THIS ONE COMING");
}
publish(55);
// check to see if the input equals "KEY MASTER"; if it does we need to go back to the EDT
// and prompt the user with a JOptionPane
if (superSecretInfo.equalsIgnoreCase("KEY MASTER")) {
int answer = JOptionPane.showConfirmDialog(
mainWindow,
"We have identified a KEY MASTER scenario. Do you wish to proceed?",
"Do you wish to proceed",
JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.NO_OPTION) {
// return a partial InputAnalysis and return
Boolean isFizz = Boolean.TRUE;
String superSecretAnswer = "HERE IS A PARTIAL ANSWER";
Integer numDingers = 5;
return new InputAnalysis(isFizz, superSecretAnswer, numDingers);
}
}
// if we get here, either KEY MASTER was not in the input or they chose to proceed anyway
Boolean isFizz = superSecretInfo.length() < 5 ? Boolean.TRUE : Boolean.FALSE;
String superSecretAnswer = "HERE IS A FULL ANSWER";
Integer numDingers = 15;
publish(100);
return new InputAnalysis(isFizz, superSecretAnswer, numDingers);
}
}
}
package com.example.swingworker.suchwow;
导入javax.swing.*;
导入java.awt.*;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.awt.event.WindowAdapter;
导入java.awt.event.WindowEvent;
导入java.io.IOException;
导入java.util.List;
公共类MegaApp{
公共静态void main(字符串[]args){
新建MegaApp().run();
}
公开募捐{
SwingUtilities.invokeLater(()->{
System.out.println(“启动应用程序”);
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame主窗口=新的JFrame(“一些简单的应用程序!”);
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.SetResizeable(真);
addWindowListener(新的WindowAdapter(){
@凌驾
公共无效窗口关闭(WindowEvent e){
System.out.println(“应用程序正在关闭”);
系统出口(0);
}
});
JPanel JPanel=新的JPanel();
JTextField superSecretInfoTextField=新JTextField();
JButton analyzeButton=新JButton(“Analyze”);
JProgressBar progressBar=新的JProgressBar();
SupersecretinFoxtField.setPreferredSize(新尺寸(200,
(int)supersecretinFoxtField.getPreferredSize().getHeight());
jPanel.add(superSecretInfoTextField);
jPanel.add(分析按钮);
jPanel.add(progressBar);
progressBar.setValue(0);
analyzeButton.addActionListener(新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
//单击后,从输入中获取一些信息并运行耗时的任务。
//运行通常需要20-30秒,我想更新进度
//在这段时间里,酒吧。
//
//还需要处理任务遇到可能错误的情况,并需要
//与EDT通信以向用户显示JOPtionPane;然后获取
//用户的响应返回并处理它。
//
//还需要处理长时间运行的任务同时遇到
//和未检查/意外异常
字符串superSecretInfo=superSecretInfoTextField.getText();
//这是我们开始长期运行任务的地方。理想情况下,这需要进入SwingWorker
//但是,需要进行一些复杂的来回通信。请参阅分析
//方法注释以获取详细信息
试一试{
InputAnalysisAnalysis=analysisService\u analysis(progressBar、superSecretInfo、主窗口);
superSecretInfoTextField.setText(analysis.getSuperSecretAnswer());
}捕获(IOEX异常){
System.out.println(例如getMessage());
JOptionPane.showMessageDialog(
主窗口,
“出了点问题”,
“流产!”,
JOptionPane。警告消息);
}
//注释上面的try catch out并取消注释下面的所有工作代码以切换
//到基于异步/非阻塞工作程序的方法
//MegaWorker analysisWorker=新的MegaWorker(主窗口、progressBar、superSecretInfo);
//analysisWorker.addPropertyChangeListener(evt->{
//
//if(evt.getNewValue()==SwingWorker.StateValue.DONE){
//试一试{
////这是在EDT上调用的
//InputAnalysisAsyncAnalysis=analysisWorker.get();
//superSecretInfoTextField.setText(asyncAnalysis.getSuperSecretAnswer());
//
//}catch(异常示例){
//System.out.println(例如getMessage());
// }
// }
//
// });
//
//analysisWorker.execute();
}
});
main window.add(jPanel);
mainWindow.pack();
mainWindow.setLocationRelativeTo(空);
mainWindow.setVisible(true);
System.out.println(“应用程序已启动”);
});
}
公共输入分析服务_分析(JProgressBar progressBar,
字符串超级分泌,
JFrame主窗口)引发IOException{
progressBar.setValue(25);
//模拟几秒钟的处理过程
试一试{
线程。睡眠(5*1000);
}捕捉(中断异常e){
System.out.println(e.getMessage());
抛出新的RuntimeException(“SOMETHIN爆炸”);
}
//现在,我们准备分析
progressBar.setValue(chunks.size() - 1);
for (int item : chucks) {
progressBar.setValue(item);
}
analyzeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Fizz fizz = fizzService.fetchFromWs(1234);
// make this guy final
final Analyzer analyzer = new Analyzer(progressBar, nameTextField.getText(), fizz);
analyzer.addPropertyChangeListener(evt -> {
// this is a call-back method and will be called in response to
// state changes in the SwingWorker
if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
try {
// this is called on the EDT
InputAnalysis analysis = analyzer.get();
// do what you want with it here
} catch (Exception e) {
e.printStackTrace();
}
}
});
analyzer.execute();
// but now, how do I obtain the InputAnalysis instance?!
// InputAnalysis analysis = null; // analyzer.getSomehow();
}
}
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.swing.*;
public class SwingWorkerExample {
private static void createAndShowGui() {
SwGui mainPanel = new SwGui();
JFrame frame = new JFrame("SwingWorker Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
@SuppressWarnings("serial")
class SwGui extends JPanel {
private JProgressBar progressBar = new JProgressBar(0, 100);
private JTextArea textArea = new JTextArea(14, 40);
private StartAction startAction = new StartAction("Start", this);
public SwGui() {
JPanel bottomPanel = new JPanel();
bottomPanel.add(new JButton(startAction));
progressBar.setStringPainted(true);
textArea.setFocusable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setLayout(new BorderLayout());
add(progressBar, BorderLayout.PAGE_START);
add(scrollPane);
add(bottomPanel, BorderLayout.PAGE_END);
}
public void appendText(String text) {
textArea.append(text + "\n");
}
public void setProgressValue(int value) {
progressBar.setValue(value);
}
}
@SuppressWarnings("serial")
class StartAction extends AbstractAction {
private SwGui gui;
private AnalyzerWorker worker;
private InputAnalysis inputAnalysis;
public StartAction(String text, SwGui gui) {
super(text);
this.gui = gui;
}
@Override
public void actionPerformed(ActionEvent e) {
worker = new AnalyzerWorker();
setEnabled(false); // turn off button
gui.appendText("START");
worker.addPropertyChangeListener(evt -> {
if (evt.getPropertyName().equals("progress")) {
int progress = (int) evt.getNewValue();
gui.setProgressValue(progress);
gui.appendText(String.format("Percent done: %03d%%", progress));
} else if (evt.getPropertyName().equals("state")) {
if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
setEnabled(true);
try {
inputAnalysis = worker.get();
String analysisText = inputAnalysis.getText();
gui.appendText(analysisText);
} catch (InterruptedException | ExecutionException e1) {
e1.printStackTrace();
}
}
}
});
worker.execute();
}
}
class InputAnalysis {
public String getText() {
return "DONE";
}
}
class AnalyzerWorker extends SwingWorker<InputAnalysis, Void> {
private static final int MAX_VALUE = 100;
@Override
protected InputAnalysis doInBackground() throws Exception {
int value = 0;
setProgress(value);
while (value < MAX_VALUE) {
// create random values up to 100 and sleep for random time
TimeUnit.SECONDS.sleep((long) (2 * Math.random()));
value += (int) (8 * Math.random());
value = Math.min(MAX_VALUE, value);
setProgress(value);
}
return new InputAnalysis();
}
}