I am trying to develop a GUI interface with swing where components can communicate with other components via the listeners. The problems I have faced are:-
Methods
- Implementing listeners
- adding listeners with listener methods using anonymous methods
- adding listeners from classes which implement listeners
Problems
- Implementing listeners creates a mess trying to operate on objects when dealing with lots of objects
- same as 1 except that the constructor requires finals for anonymous methods
- Cant operate on objects outside of the listening class without resorting to static references.
This is really frustrating because how can I get a MouseListenerClass to draw on a JPanel that is part of a separate JFrame class without passing the JPanel to the mouseListenerClass to do operations on it.
The only method I seem to have got working is creating a Enum called MouseState, when the mouse event MousePressed is fired it sets the static Enum mouseStatus to pressed, then the JPanel paintComponent method checks the Enum mouseStatus and paints if theres a press.
This seems like the wrong way.
Is there another way?
Updated to reflect the comment by Cyrille:-
Thanks @Cyrille I had to amend your code by using casting, but the premise still works. ' public void mousePressed(MouseEvent e) {
PaintPanel p=(PaintPanel) getTargetPanel();
p.setMousePressed(true);
p.setMouseCoords(e.getPoint());
}
public void mouseReleased(MouseEvent e) {
PaintPanel p=(PaintPanel) getTargetPanel();
p.setMousePressed(false);
}
public JPanel getTargetPanel() {
return targetPanel;
}'