Given an array of "modules" which are instances of various different JPanel extensions, how can I "run" each of them in sequence, so that the (i+1)st one opens when the ith one closes?
I'm creating a psychology experiment based on inherited code. The inherited code implements a number of experimental tasks, each as a separate class. Each of these classes extends JPanel and has a method "go" which, when called, creates a JFrame and uses it to display the contents of the module. So, for instance, I have classes like:
public class Module_1 extends JPanel implements MouseListener, KeyListener {
...
protected JFrame frame;
...
public void go() {
frame = new JFrame();
...
}
...
}
public class Module_2 extends JPanel implements MouseListener, KeyListener {
...
// same general format as above
...
}
Then I have a series of modules, each one belonging to one of the above classes. I want to run go() from the first module, which will create a JFrame. When this JFrame is closed, I want to run go() from the module, and so on. What's the best way to do this?
My approach was to add a callback to each module, e.g.
public interface Callback {
public void call();
}
public class Module_1 extends JPanel implements MouseListener, KeyListener {
...
protected JFrame frame;
...
public void go() {
frame = new JFrame();
...
}
public void setCallback(Callback c) {
frame.addWindowListener( new java.awt.event.WindowAdapter() {
@Override
public void windowClosing( java.awt.event.WindowEvent windowEvent ) {
c.call();
}
});
}
...
}
// and do the same for the other modules
Then, I attempted to create a utility which would take an array of modules and run through them in the manner described:
public class Panel_sequencer {
private Object[] modules;
public Panel_sequencer( Object[] Ms ) {
this.modules = Ms.clone();
}
private void iterate( int idx ) {
if ( idx>=this.modules.length ) {
return;
} else {
Object M = this.modules[idx];
M.go();
M.setCallback( new Callback() {
public void call() {
System.out.println("Completed module "+idx);
iterate( idx+1 );
}
});
}
}
}
However, this doesn't work because go() isn't defined for type Object. Is there a way around this? Or should I be using a different approach entirely?