Best way to handle JFrame components from outside class - java

I was developing a swing application which calls multiple methods & initializes different classes.
Also I have multiple threads in which they process intermediate results. My requirement is to display that intermediate data on some labels and text boxes on the fly.
Please help me which of the below approach is best in terms of memory and performance.
I can have setter methods for all my labels and text boxes. So that I can call these methods using that swing class object but in that case I need to pass the swing class object to every class wherever I want to set the data to labels.
Another way is I can create public static object of my swing class and I would call it from any class whenever I need to set the label text.
First method creates more overhead as I need to pass the my Swing class object to other classes.
Second method is easiest way but creating static objects might create confusion as this application contains threads.
I just want to know which one to go for and why?
Otherwise if anybody have worked on some complex swing app development - how did you manage these kind of issues?

This example is typical of your first approach in a multi-threaded context. For expedience, the model and view are tightly coupled: each worker thread receives a reference to the label it should update. The alternative is loose coupling: each view registers to listen to the model, which notifies all registered listeners using the observer pattern.
This simpler example uses both approaches:
Tight coupling: The worker obtains a reference to its target label in an enclosing scope.
Loose coupling: The enclosing view registers a PropertyChangeListener, which the model uses to signal the view via setProgress().
You'll need to decide which is important in your application. I agree with #JB Nizet's comment about the second approach.

Why dont you use the 2nd method with Singleton principle, where you can use the same single instance of the swing class, so there will be no use of using static , and its sometime confusing cause we are uncertain of the order in which the JVM loads the static members...

Think of a GUI as a model with a view. The GUI components make up the view, while you create model classes that represent the model. Changes to the values in the model are reflected in the view. The rest of the application interacts with the model, and not the view.
Here's one example from a Java Spirograph GUI that I did.

Related

What is a nice way to bind buttons to model-methods through a controller in Java using Swing and MVC-pattern

I have tried to adhere to the mvc pattern in the java code that I have written. I want to keep the view and model independant of the controller and from each other. I am also trying my best to use interfaces to keep things modular.
My view has JButtons that I want to "bind" to specific methods in the model through the controller. I have tried two approaches to still keep the view independent of controller:
Registered the controller as an ActionListener to the view-object. Pros: The void addListener(ActionListener listener) abstract method encapsulates this behaviour in the view interface, so more buttons can be added without changing the interface. It also decouples the controller from the view, since it does not know anything about the actual buttons in the view. It is also easier to add more views or more controllers, so it follows the open-closed principle well. Con: For the controller to know the nature of the ActionEvent, I have only been able to come up with using the ActionEvent.getActionCommaned() in a switch statement, so mapping each case to its' corresponding method in the model. This seem unsafe and prone to cause irritation, since it seems like bad practice to match strings like this.
I also came up with adding public addActionListener(ActionListener) methods for each button in the view, like addGasButtonListener(ActionListener). Then doing something like view.addGasListener(e -> model.gasVehicles(view.getGasAmount())) in the controller. Pro: This seems like it reduces the uncertainty of matching strings. Cons: It means I have to add these new methods to the view interface, and each time a new button is added I have to do the same, making it difficult to add new views that does not have anything to do with some of the methods.
Main question:
I prefer the first method since it seems better to me, but I still would like to find a way to avoid matching strings, and find some nice way to do it (more similar to the rigidity of the second way of binding buttons to methdods). Is there?
Follow-up (less important) question:
I should also mention that my controller contains an inner class TimerListener implements ActionListener, that contains the loop of the app that acts on ActionEvents from the Timer. It also acts on ActionEvents from buttons if approach number one is used, which is why my follow-up question is: how would I seperate this main loop that only cares about the timer, from the switch statement used to act on button events. Since the ActionEvent.getActionCommand() is null almost all the time, it would be nice to seperate the two. Is there a approach that would let me do that?
I don't really see the value of working with ActionListener instances in the first place.
From your own example:
view.addGasListener(e -> model.gasVehicles(view.getGasAmount()))
You don't do anything with the actual event
In case you decide to use a different UI element in the future that doesn't fire ActionEvents, you will have to change the type of the listener.
I would rather expose a custom listener/callback that the controller (or model) can register on the view:
void onGasAmountChange(double gasAmount);
That being said, you might be focusing too hard on having a model, view and controller. If you look at more complicated Swing components (JList, JTable, ...), they have a view component and a model (ListModel and TableModel).
You could do something similar and create your own model for your view, and let the view call the necessary methods on the model directly (just like it happens for those Swing components).
That avoids having to write a bunch of one-liner listeners that basically delegate to the model.

Java make components talk to each other

Let's say I have a gui, and the gui is composed of two parts where each part has its own class.
So one class contains a JLabel.
And second class contains a text field with a submit button.
How would I go about making those two components talk to each other?
This is of course a simple example, but if I have two classes where I use one for submitting data, and one for showing the submitted data, then how do I make the two components communicate?
Some thoughts:
Don't add such bindings to the GUI classes, look for a pattern like MVC
Unidirectional change propagation (input -> output as in your example) is usually never problematic, but in many cases, full synchronization of editable component groups is required. So one may keep that in mind during development of the simple case for good reusability of any custom class or interface.
Avoid infinite circular updates with a flag, rather than with a comparison of component values.
Whatever you do, keep things separated and whatever pattern you use, don't add bidirectional references (e.g. among GUI class <-> controller)
Regardless of MVC, there could be a controller class, getting all necessary references to the UI objects (i.E. JPanels with nested JTextFields and JLabels, etc.) via constructor.
On construction, that controller can attach itself to those nested components.
The controller should preferably contain nested, inner or perhaps anonymous classes for implementing the listener interfaces, rather than adding the listener interface to the controller itself. First, to encapsulate these listeners and second, to avoid the event source distinction, if the same interface needs to be implemented for multiple components (sources). These listener implementations (perhaps pretty generic PropertyChangeListener's) could then act as, or use mediator objects (as mentioned), for updating other components.
If you have a submit button, you can add an action listener to it. When clicked you can call a method in your other class that will receive the string and then display it on your JLabel. However having multiple classes for different components isn't usually a good idea, and having a MVC like what Sam said is much better.
Class with JTextArea
//Have this object created
JLabelClass JLC = new JLabelClass();
//When submit button is clicked run this
JLC.displayText(JTextArea.getText());
Inside Class with JLabel
//add this method
public void displayText(String text){
JLabel.setText(text);
//Refresh Gui and display stuff....
}
Hope this helped... Sorry about the formatting I'm still new to StackOverflow

Java; Multiple MVC and Swing Relationships Best Practice?

I am attempting to develop a "Person database" Java Swing application, using MVC design paradigm with Observer/Observable. Here is a simplified abstract of M/V/Cs I am using:
App
AppModel
(Empty right now, possibly i'll store certain static application info such as version number here)
AppView
(Creates a JFrame and a few other Swing components)
AppController
(Instantiates AppModel, AppView and also a PersonController and a PersonListController)
Person
PersonModel
(Stores info for 1 person)
PersonView
(Displays a number of form fields inside a JPanel (i.e Name, Age, Phone number). Observes PersonModel.)
PersonController
(Instantiates PersonView. Observes PersonView. Instantiates PersonModel. Updates PersonModel.)
PersonList
PersonListModel
(Stores a list of Persons)
PersonListView
(Displays a list of persons with appropriate Add / Delete buttons. Observes PersonList.)
PersonListController
(Instantiates PersonListView. Observes PersonListView. Instantiates PersonListModel. Updates PersonListModel)
Also, a 'bootstrap', where the app starts. It creates a new AppController.
In the real application, there will be more (and different) Model/View/Controller objects but I want to keep this example simple.
I dont understand how I can go about 'merging' these seperate views into one UI while maintaining a good seperation of concerns.
Take for example the PersonListView. IMHO it doesn't need to care about the AppView (with the JFrame etc). PersonListView just needs to look at its own model and update itself accordingly. However, I cannot enforce that because the PersonListView's own Swing components need to be added to the Swing components of another view, the AppView.
So at the moment the AppController is instantiating its own View, plus indirectly a PersonView and PersonListView (via instantiation of their controllers). AppController then grabs the 'main' Jpanel for each view, grabs the 'parent' Swing components they should be added to on the AppView, and adds them.
This just doesnt seem the right way to do it to me. Im pulling Swing-related members from their hiding places and messing with them around inside a controller. In fact instantiating the model and view within the controller seems bad too, but I cant figure out a better way.
I've seen enough 'simple MVC' tutorials recently that I'm dreaming of the bloody things - but not one tutorial seems to go into the relationships of multiple models, views, controllers, especially where it concerns Swing. Maybe I am wrong and the App should have just one view? Maybe I need a 'Relationship' class that sort of takes every single Model/View/Controller and instantiates stuff appropriately?
Any advice would be most appreciated as Im completely at a loss!
This is where a strict MVC paradigm falls down (in Swing anyway, and it may explains why Swing is written the way it is).
Swing combines the view and control elements together, leaving the model separate. That means, you are free to add a view to any other view and the control follows (the model remains dynamic).
I have a developer who insists on using the strict approach to MVC and they still can't tell me the order of precedence. ie should the control know about the view or should the view know about the control - which one plugins into the other. Personally, I'm to lazy and simply follow the Swing implementation.
To my mind, if you want to follow a strict MVC, I'd basically allow for a public method in your controller that allows access to the overall view (say a JPanel with all the components on it that makes up the view for example).
Think about the JComboBox or JSpinner for example. They both have a number of components that make up the view (editors, buttons, etc), but you have single access point, the component itself...
Your next problem is going to be how to combine various views into a single over all view.
Personally, I would create a group controller of some kind that allowed you to supply the various, known, controllers together (setPersonList for example), as the "master" controller is going to need to know about these other controllers any way, as it needs to know how to layout them out.
IMHO

Some questions about OOP in Java

I have a GUI class with a menu of buttons and textfields. Depending on what choices that is made in the menu and the input, methods in the GUI class are calling methods in the Logic class to send the input and create new objects of Customer class and Account class and so on.
To be able to communicate between the GUI- and the Logic class, I first create an object of the Logic class and I do that inside the GUI class, since it's here I have my main method. It this the best way to do it? Do I need some kind of reference variable between GUI- and Logic class or just use the reference when the object was created in the beginning of the GUI class? I guess to be able to communicate with a class, it must be an object first!? Thanks!
Logic logic = new Logic();
logic.addCustomer(name, number);
Ideally you shouldn't directly create the logic class.
You should break down the functionality into a number of small classes, each of which satisfy a responsibility.
A simplistic way would be for the GUI class to create listeners which listen to the user events. In response the to the use event they fire events that your logic registers itself for. Then when the event is received the logic class can perform the functionality.
You should read about observer pattern, event driven design...
You can read about event driven programming here http://en.wikipedia.org/wiki/Event-driven_programming .
I would instantiate the Logic class outside the GUI, but pass it as an argument to the GUI constructor. It's nearly equivalent to what you are already doing, but I think it makes it clearer that the GUI uses a Logic object. Also, it's possible that Logic does some other things before/after the GUI starts/closes; it might not be the case now, but it could be true in the future if you extend your program.
Many other answers tell you to look at MVC, but that might be overkill for your project. It can decrease complexity for a large project, but increase it for a small one.
EDIT:
Logic login = new Logic();
...
MyGUI gui = new MyGUI(logic);
...
I would suggest you do some researches on the MVC architecture. Your GUI (view) shouldn't interact directly with your model (logic). Implement a controller that will get the "signals" from your view and will be in charge to create your "logic objects" and work with them.
You can create on object of type Logic in your main and store a reference of the object in your Window object - so you can access your Logic object as long as the window exists.
You should look up the Singleton design pattern for such trivial scenarios.
By default, Java uses Reference variables. Hence, if you instantiate your object in GUI class, make sure you send the object via method calls to your processing class.
Alternatively, you can look into singleton classes, which will return only one instance of the class. Inside that class, instantiate all the objects that you will need globally, and re-use that instance throughout your program.
Generally you can. If your application is very simple.
But this approach is not scalable. As your application gets more complex it became much harder for development and support. Try to consider Model–view–controller pattern to define a best way for your design. (according to your nick name I'll take a risk to propose an alternative link)

java / gwt UI coding - clean code

i've started on some basic java coding with gwt, and im getting a bit concerned about the heft of my main class.
For instance - how does one compartmentalize the keyhandlers, since they trigger a number of changes to the UI, how could i move this into a separate .class file and still be able to access all the various widgets in the main class, without having to pass everything to the handler (ie. all the widgets i manipulate after the click event).
i've googled but didnt come across any particularly good examples - know of any readily legible code-bases i could read to see how it should be done? (gwt's own tuts are pretty basic, and just kitchen-sink every thing into a single file)
thanks!
I hate to say something so unimaginative, but MVC works--it's not the ultimate, but it can start getting you organized.
EDIT: While searching on a semi-related topic, I came across this which has similar ideas to mine but goes into more detail.
What that means in terms of GWT is that you should think of just laying out your GUI components in one class, put all your event handling in a second and put your object model objects separate from the other two.
One way to accomplish this is to make most or all the controls on your GUI public members. This sounds kind of lame, but their usage is encapsulated inside the controller so it's not like you have uncontrollable access--in fact your access is clearer/better defined than if all your members were private but your view code was combined with the controller.
Specific tricks:
Have listeners be their own class. You can often reuse them-- in other words, avoid anonymous inner classes. I sometimes create a listener class and instantiate a new instance for each button/control that needs to have a similar effect when pressed. If I need it to act slightly differently for a given button, I'll pass something into the constructor of the "special" handlers so that they know to act a little differently. You can also create different handler sub-classes if necessary--I'm just saying don't forget that event handlers are classes, you can use inheritance and everything if need be.
One Very Old GUI Trick I learned a long time ago, try not to have various mini-handlers modifying the GUI in different ways, instead have all the "active" buttons and controls set a state within your GUI and then call a single method that applies that state to ALL the controls on your GUI. When you get beyond a trivial GUI this can be a life-saver. If I'm not being clear, leave a comment and I'll leave an example for you.
Property sheets:
There is a special case for GUIs--the property sheet style GUI. I've done a LOT of these and they are irritating as HELL. They tend to have dozens or hundreds of controls on them, each GUI control tends to be tied to a specific field in your model and there are just hundreds of lines of copy and paste boilerplate code connecting them, each group copied and pasted with a few items changed--at minimum it's like 3 lines of code per control (Create control, copy value in and copy value out).
I always write these with a "Smart" controller--one that can intelligently bind the control to some data without any unique code. This can get tricky and if this is your problem let me know in the comments and I can give you some general advice as to some tricks you might try. I've gone from a minimal reflective solution to a full-on XML based solution. Were I to do it again, I might consider annotation-based.
Example of MVC:
Note, this is just an example, there are a MILLION ways to do MVC.
In your MAIN:
Instantiate MyView
Instantiate MyModel
Instantiate MyController(myView, myModel)
myView.setVisible(true)
in MyView
probably extends Frame
Most components are public final (public final Button b=new Button())
If public members make you nervous, use getters--same EXACT effect as public final members with a little extra syntax.
Remember that you can set final members in your constructor.
May have general methods such as reset(), but MyController may be a better place for this.
in MyController
saves references to myView and myModel
adds listeners to myView where necessary (see advice on listeners above)
configures myView based on state of myModel
when "done" button pressed, copies state from myView to myModel
notifies myModel that it's data has been updated and destroys itself.
in MyModel:
This would be a typical model class, it would contain your business logic (mostly not used as part of the GUI, that's more like GUI logic in MyController. The controller would tend to set values in your business logic then call some method like updated() to cause some business logic to take control. It should know nothing of a GUI--this is your "pure" business class.
Sometimes the GUI might call an update() or some other method to trigger some data change and then reload the GUI controls from the Model--this is a fairly good way to integrate your business logic with your GUI without your model knowing about the GUI...
Also, as I said above, I would put more work into MyController if I was working with property sheets just due to the sheer number of lines of boilerplate that you end up with if you aren't smart about it.
Note that View and Controller are nearly always paired. You can't just replace a Swing view with a web view and expect the controller to remain unmolested--but the model should not ever change for the view or controller.
You should take a look at the best practices for GWT applications first:
http://code.google.com/events/io/2009/sessions/GoogleWebToolkitBestPractices.html
One of the concepts they talk about is that of MVP (not MVC) to structure your application. There's a sample project on Google Code that you can look at to understand how to structure a GWT application in this way:
http://code.google.com/p/gwt-mvp/

Categories

Resources