The second type of the V parameter in SwingWorker<T,V>
used to perform intermediate results using these publishing methods and SwingWorker processes. It could be your own class. Here is an example based on a published SSCCE (short for clarity):
class Progress { private int task; private int element; public Progress(int task, int element) { super(); this.task = task; this.element = element; } ... } public class Model extends SwingWorker<Integer, Progress> { ... @Override protected Integer doInBackground() throws Exception { ... publish(new Progress(i, ii)); } }
EDIT: Process Method Implementation Example
@Override protected void process(List<Progress> progressList) { for (Progress p : progressList){ System.out.println(p.getTask() + " : " + p.getElement()); } }
EDIT: UI Update Example
Here is a slightly modified version of the working implementation, similar to the example shown in the SwingWorker manual. The only changes are introducing the textArea
member and updating the call to setProgress()
in doInBackground()
. The progress
property is used to update the progress bar, process()
used to update the text area.
public static class Model extends SwingWorker<Integer, Progress> { private HashMap<String, Number> GUIparams; private int session; private int ticks; private JTextArea textArea; Model(HashMap<String, Number> KSMParams, JTextArea textArea) { GUIparams = KSMParams; session = (Integer)GUIparams.get("experimentsInSession"); ticks = (Integer)GUIparams.get("howManyTicks"); this.textArea = textArea; } @Override protected void process(List<Progress> progressList) { for (Progress p : progressList){ textArea.append(p.getTask() + " : " + p.getElement() + "\n"); System.out.println(p.getTask() + " : " + p.getElement()); } } @Override protected Integer doInBackground() throws Exception { int i=0; while(!isCancelled() && i<session){ i++; int ii=0; while(!isCancelled() && ii<ticks){
Here is a demo initialization:
final JProgressBar progressBar = new JProgressBar(0, 100); final JTextArea textArea = new JTextArea(); final JButton button = new JButton("Start"); button.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { HashMap<String, Number> map = Maps.newHashMap(); map.put("experimentsInSession", 10); map.put("howManyTicks", 5); Model task = new Model(map, textArea); task.addPropertyChangeListener( new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { if ("progress".equals(evt.getPropertyName())) { progressBar.setValue((Integer)evt.getNewValue()); } } }); task.execute(); } });
source share