When writing a graphical interface, using Java, what’s the appropriate way of switching between the different windows of the application, when clicking a button for example? I.E. what are the windows supposed to be, JPanels, JFrames…? And how do all the components ‘see’ the ‘domain controller’ (the class that links the graphical package to the application logic package)?
Any guide or reference would be appreciated.
You start your application with your
Controller. In the constructor of your controller, you are going to initialize the first GUI you want to open, lets sayGUI_A:As you might notice, I called the constructor of
GUI_Awith one parameter:this.thisis referencing the instance of the current class, sothisis type ofController. The constructor ofGUI_Ahas to look something like this:This is a simple way to get the GUI known to the
Controller.The next thing you would do is displaying
GUI_A:If you now want to handle button-clicks, you would do it like this:
First, you add the action-performed method to your button. And, as it is best practice in MVC, you don’t want to do logic in your view/GUI. So you also create a corresponding method in your
Controllerfor the action-performed, and call it from your GUI:Usually you don’t need to pass the ActionEvent-var to the Controller, as you will not need it often. More often you would read a text out of a TextField and pass it on to your Controller:
If you now want to access some fields on your
GUI_Afrom theController, be sure not to mark the fields as public in your GUI, but to create public methods which handle how to display the values.