I wrote an aricle a couple months agoMY POST
but I want to make some changes to I. Now all my code is worked out in the Swingworker class. But I want to use the MVC methode and use the observer pattern to update my variables in the view.
Now i have something like this
public class CopyFrame extends JFrame {
private JTextarea textArea;
private JProgresbar progresbar;
public CopyFrame(){
progresbar = new JProgresbar
textArea = new JTextarea();
progresbar.setMaximum(100));
/*in this method I added the components correctly*/
addComponentsCorrecty();
new Task().execute();
}
class Task extends Swingworker<Void,Void>{
/*Dp this 10 times*/
Files.Copy(source, destination);
progresbar.setValue(progresbar.getValue + 10);
String info = String.format("%s is completed", source)
textArea.setText(textArea.getText + "\n" + info)
}
}
and i want to create something like this
public class CopyFrame extends JFrame {
private JTextarea textArea;
private JProgresbar progresbar;
public CopyFrame(){
progresbar = new JProgresbar
textArea = new JTextarea();
progresbar.setMaximum(100));
/*in this method I added the components correctly*/
addComponentsCorrecty();
Task task = new Task();
task.addObserver(this);
task.execute
}
@Override
public void update(){
progresbar.setValue(progresbar.getValue +10);
textArea.setText(textArea.getText + "\n" + task.getInfo)
}
}
class Task extends Swingworker<Void,Void> extends Observer{
private String info;
public Task(){
doTask;
}
public void doTask(){
/*Dp this 10 times*/
Files.Copy(source, destination);
info = String.format("%s is completed", source)
setChanged();
notifyObservers();
}
public String getInfo(){
return info;
}
}
How can I do this? because I can't extend from 2 classes. I want to update the progresbar from another class (TASK)
what Is my best option
SwingWorker
provides a form of a observer pattern in the form of aPropertyChangeListener
.This provides notifications about the change in state (running/done/etc) and progress changes.
For example:
Getting a bit tired of re-writing the
PropertyChangeListener
, I did create a simple adapter which provided more direct event notificationThis allows me to override the methods that I'm actually interested and reduces the amount of repeated/boiler plate code I have to keep writing
Remember, the Swing bases "listeners" are actually a form of an observer pattern ;)