Java separate MouseListener and performance - java

Writing a game and using mouse events for the first time, but as I play with them, the various methods are getting bigger. I want to separate the listening stuff into a diffrent class, but I will still need access to my various objects that are stored in my main class (where the listener methods currently resides having used implements)
Another thing I have noticed, is that when performing the events, they seam to have a very variable perfomance speed, is there any way to improve this?
any help / suggestion are very much appreciated
Thanks

Move the fields from the main class to a "model" class (which contains a model of your game).
In the main class, create the model and then pass it to the listener.
As for the performance: I suggest move the mouse handling in a thread which waits for a signal (see Object.notify()). In the listener, update the current coordinate (use AtomicReference and a Point object) and then send the signal. This way, you handler can do its work as fast as possible but when it can't keep up with the mouse, it will skip ahead (instead of lagging behind).

Related

How to return a value, but continue a loop?

I apologize if there's already an answer to my question, but I couldn't find a solution. I want to make an application which basically has two text fields and two combo boxes where you choose a increment step, and when you click start you can see the numbers change in different steps in each text box every second. I managed to do it in a single file using two threads, but I want to do it the MVC way. In other words, I have a Controller class which handles the View click, and runs a thread from my Model class, which returns the value on every iteration of the loop, and then I pass that value to the JTextField.setText() method to visualize it. In a single class I can easily do it in the loop itself:
while(!isInterrupted()){
count += step;
textField1.setText(count);
sleep(1000);
}
However, I think there are two ways to do it. Pass a reference of the View to the Model, and manipulate the text field from the Model class, which I feel counters the idea of the MVC to separate the model and the view. Or use a Callable or a Future somehow (I don't really know how they work, and if they will work in my case) to pass the count value on every iteration of the while loop to the Controller, which in turn is going to pass it on to the View.
How do you think I should do it, and is there any other (better) way of doing it?
You should read up on Event Handling in Java and Listeners.
The basic gist is: You want your GUI to be updated. More specific - you want it to be notified, when to update itself.
Solution : Listeners.
What's that? I linked to the oracle lesson in my comment, but basically you "register" your gui to be notified of some sort of event at the model. That is done by providing some Interface, that your gui will implement - for example an interface that declares a method 'onMyValueChanged( int oldVal, int newVal )'. You will then add a reference to the gui at the model. The model would then use that reference to call the Listener interface when appropriate.
Mind that you should manipulate GUI Elements from the GUI-Thread (aka "EDT" = "Event Dispatch Thread"), only. So you will probably have to do some inter-thread communication in the listener implementation.
A convenient means of doing all the above is using SwingPropertyChangeSupport. See How to write a PropertyChangeListener for examples and further explanation.
Another way of meeting your requirement would be to use a SwingWorker and publish changes in the process. A good starting point would be this tutorial from oracle: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html
And this section about the EDT is definitely for you: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html
As a sidenote, I can really recommend those Oracle Lessons. They are an informative read and they are free. They really helped me a lot when I was a beginner and they still do frequently as look-up for things I do not use frequently.

ActionListeners, multiple field updates, and reloading user GUI selections from a file

I have multiple places where I convert between one coordinate system and another. In each case there is a cosine/sine calculation between, let's call them x, y and x', y'. These are all JFormattedTextFields.
If the user enters a value in any of the 4, an ActionListener is called. Lets call the fields fieldx, fieldy, fieldx1, and fieldy1. If the user enters anything in fieldx or fieldy, I HAD keyboard and focus listeners (the same one for all four fields) that would update fieldx1 and fieldy1 from the current values in fieldx and fieldy. If the call to the listener was from fieldx1 or fieldy1 it would calculate fieldx and fieldy.
Then I decided to save fields chosen (including a bunch of check-boxes on/off and some spinners' values) in a config file (new requirement after development). I thought that by setting values and states all would be fine BUT certain things were not happening (behind the scenes). I decided that part of this is that the triggered methods by various checking and entering and etc were not happening because the fields did not trigger keyboard and focus listeners when they were set by a piece of code.
After reading online I changed all the KeyboardAdapter to ActionListener and after I set the value I call postActionEvent() on the fields I mentioned above and now all the background stuff happens (though order is an issue and I'm going to save extra information about state to update this properly). I made this change because I thought it would be more difficult to fire off so many fake keyboard events?
There are probably more clever/smart ways to do this but for now I'm trying not to touch too much code.
Does anyone have a suggestion on a way to save the state of a panel and refresh this (the current object, the panel)?
If I continue to do it in this way, can someone suggest a way to MINIMIZE the times the ActionListener fires? It seems to fire so often it is ridiculous!
Should I instead do things as suggested here?
Should your class implement ActionListener or use an object of an anonymous ActionListener class
That seems like a lot more coding involved but a lot more precise in what triggers when...
If this kind of question/discussion is out of place here, just let me know :). Just typing up this page has made me think of more things to read up on and to try.
I'm trying not to touch too much code.
This is a foundational mistake; the trash can is an important design tool, and one or more minimal examples will be invaluable in learning to compose more complex applications.
Does anyone have a suggestion on a way to save the state of a panel and refresh this (the current object, the panel)?
Using the Model–View–Controller pattern, the program's data should be stored in a suitable model, and transformations should be done when model elements are rendered in the view; the Converter example shows how to manage custom events, and this example expands on the topic
If I continue to do it in this way, can someone suggest a way to MINIMIZE the times the ActionListener fires?
As suggested in the original article, use Action to encapsulate behavior. See Java SE Application Design With MVC: Issues With Application Design for a deeper examination of the problem.

Handling mouse input in a multi threaded game

First of all, I apologize for the unruliness of this question, I tried to explain everything that was essential without leaving anything important out or giving anything extra, but I may not have done the best job. I would post code but there is just way too much of it tot be able to post.
I am developing a game in Java, using no external libraries. I have a main class that also handles my Jframe. It sets everything up, such as size, title, etc, then starts a new Thread that handles everything else that's not basic setup. It's an loop that runs until the game is closed. It basically consists of update, then render. Those methods call the corresponding method in a state managing class, which contains an instance of a custom GUI class that I extend for all of my GUIs. I have it declared as a GUI rather than one of GUI's subclasses so that whenever I need to switch GUIs I can simply swap in a new one seamlessly. So the basic flow of the program is the threads update() -> state manager's update() -> GUI's update(), then the same thing for render. So my question is, since I have the Jframe declared outside of my thread, what is the best way to pass mouse input into the thread? If there was just a single object that I could grab and send into the GUI, it should be simple. But since there could potentially be multiple MouseEvents coming from the MouseAdapter between each frame, I can't seem to wrap my head around how to do this. The best idea I've come up with was to make an array of MouseEvents, then iterate through it in the update method. However, for some reason Eclipse kept giving me errors when. I tried to make the array, so I gave up on that in about a minute.

Best way to handle JFrame components from outside class

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.

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