I’m just starting to work with Java Swing again and I have the same problem as last time.
I want to write a program which reads some user input, executes an algorithm and displays the result. The program has to work with two different user interfaces (console and GUI with Java Swing).
Currently I have a packet of classes with the algorithm (i can just pass in the user input and fetch the result), a class which contains the main class, a class for the console interface and a class for the GUI (which extends from JFrame).
Some code:
public class Algorithm {
//a lot of code
}
public class MainClass {
public static void main(...) {
Algorithm algorithm = new Algorithm();
//use either console or GUI and read user input
algorithm.execute(user input);
algorithm.getResult();
//display result on console/GUI
}
}
public class GUI extends JFrame implements ActionListener {
}
My Problem is that I don't know how to pass the user input (text, scalers and radio buttons, button) from the GUI to the algorithm and how to display the result on the GUI.
Do I have to pass an instance of Algorithm to the GUI and call the methods of Algorithm from GUI?
Or is it possible to implement the ActionsListener in MainClass (where I have an instance of Algorithm)? If I choose this way of implementation, how can i pass the result of the Algorithm back to the GUI?
Or should i change the whole implementation? 😀
Short answer: Don’t (at least not to the Main class).
Long answer: There is a pattern called Model-View-Controller (MVC) which explains how to get data from the user, do something with it and display it again. This link (and the whole site in general) is a good point to start: http://martinfowler.com/eaaDev/uiArchs.html
Applied to your code sample:
Algorithmplays the role of the model here andGUIis a combination of controller and view.