I am working with Swing for some time now and I am constantly thinking about if my management of components is really useful and a good way to do so. Let me explain:
public class Main extends JFrame{
private MyPanel panel = new MyPanel();
public Main(){
// do something
}
public JButton getButton(){
return this.panel.getButton();
}
}
public class MyPanel extends JPanel{
private JButton button = new JButton();
public MyPanel(){
// do something
}
public JButton getButton(){
return this.button;
}
}
public class Controller{
public Controller(JFrame frame){
frame.getButton().addSomeListener(new ExampleListener(frame));
}
}
public class ExampleListener implements SomeListener{
private JButton button;
public ExampleListener(JFrame frame){
this.button = frame.getButton();
}
@Override
public void actionPerformed(ActionEvent event){
// do something
}
}
My question is about the way I work with event listeners. I used to save a reference to each component that needs some listener in the top of my hierarchy (in this case the frame) and give the frame as parameter to a central logic class. The central logic class gives always a reference to the topmost hierarchy component to the listener and these "extract" needed components with help of getter methods. As you can see, I use a nested "getButton()" method inside the frame. I really would like to know if there are some drawbacks or similar with this management. If there is, can you recommend some good ways to organize components?
PS: I know that Swing works good with the MVC pattern, but I don't really know if I managed to do so.
PPS: I know that it is considered bad practice to extend JComponents without overriding desired features. This here is only for demonstration purposes.
Sorry if similar question already exists. :)