I am working on a GUI application with Java and SWT.
I have createad a main window with a canvas in which I load an image (well it's a PDF page converted to image).
I have attached a PaintListener to the canvas and when i drag the mouse onte the canvas I am able to draw a rectangle.
When i release the left button on mouse, I want a dialog window to came out to "fine setting" the rectangle area, so I made a dialog with 4 spinner (x, y, width and height).
Now I want to click on the spinners and the canvas redraw the changed rectangle area.
I tried to pass the canvas object to the dialog window and attach a second paint listener to it (So I have one paintlistener from MainWindow.java and another from Dialog.java), but it's no working.
The problem is that I have multiple rectangle drawn on the canvas, and if I call canvas.redraw() from dialog window, the rectangles already drawn on canvas "disappeared".
What is the best practise in such situation?
I thinks to put the dialog window "in the toolbar", that is put the 4 spinners in the toolbar (or another area in the main window) so I have only one paint listener and get rid of the dialog, but I prefer the dialog 'cause it is impratical to drag a rectangle onto canvas and then move the mouse to click on toolbar.
Thanks in advance, Mauro
0
votes
1 Answers
0
votes
Your main window should implement custom listener for example:
public interface PreferencesListener {
public void updatePreference(PreferencesEvent e)
}
Then create a manager which control updates:
public class PreferencesController {
private static PreferencesController instance = new PreferencesController();
private List<PreferencesListener> preferencesListeners;
private PreferencesController() {
preferencesListeners = new ArrayList<PreferencesListener>();
}
public static PreferencesController getInstance() {
return instance;
}
public void addPreferenceListener(PreferencesListener listener) {
preferencesListeners.add(listener);
}
public void notify(int x, int y, int w, int h) {
PreferencesEvent e = new PreferencesEvent(x, y, w, h);
for(final PreferencesListener listener: preferencesListeners) {
listener.updatePreference(e);
}
}
}
At the moment of creation main window register it in controller:
PreferencesController.getInstance().addPreferenceListener(this);
When you change value in dialog trigger notify:
PreferencesController.getInstance().notify(x,y,w,h);
And then finally implement updatePreference(PreferencesEvent e) from PreferencesListener. From this moment whenever values x y w h are changed your window will be notified. From my point of view it's a good solution because your window and dialog don't even know each other exists, and you could easily add another component that react to preference change.