Is there any method to be followed before writing code for a GUI program? For previous programs, i had algorithm and/or class diagrams before writing code for the normal programs(those done before learning GUI)Should we follow anything similar while making GUI?I just made a small game(Book cricket) which involves using data stored in files and some computations.
I have completed the game just by making one thing at a time and so, i have lots of code. I just wanted to know if there is any procedure while making GUI based applications that can be followed for optimizing and making the code easy to read and debug?
To be more specific:
1. Should we design all panels in different classes?
2. If there are actionListeners for the objects, then should i put them along with the creation of the objects?
3. While using cardLayout to manage which panel should be visible, i often had to convert all the fields related to a panel static so that i could modify fields in one panel on actionEvents in some other panel.
Is this a standard thing to do or should i be doing something different.
4. I use the terminal to write my codes. Since i have just started working on GUI, i thought working with terminal would be a more better learning experience.Should i continue using terminal or switch to some IDE like eclipse/netBeans ???
Thanks
What kind of program does you want to write : it is a game or just an application ? For each kind of thing, often, there are patterns to do this. Moreover, for each kind of game or application, there are many ways to build framework. In other word, it's diversity, and depend well on program.
Nevertheless, in general way, there are some suggestion when you start to design your program. For example, you can apply MVC (Model-View-Controller) to this by :
View : this is a GUI and just a GUI. it contains code to build a GUI, build action listener for some objects such as buttons .... when some action appears on this GUI, for example, someone click a button, it will call appropriate action in Controller. So, View, in fact, doesn't really understand anything. It doesn't know (and doesn't care) this button or that button should do what.
Controller : connect between View and model. It will initialize View and Model. It will receive action from View, and call appropriate method from model and return result again to view. Controller knows how to control flow of data from user.
Model : a class with bunch of action that your application can do. Model doesn't really know, how to operate your program, it just holds the state of program.
Hope this help :)
Related
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.
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.
My Java application is not very big, but I would like to do it the "right way". Looking for suggestions to not make a big mess...
I am using Swing, the Swing Application Framework and H2 database.
It is a single frame application with different tabs. Most tabs will reflect some aspects of the data in the database. Some of them will be able to change it. Some tabs will have buttons or actions that will redirect to another tab... that's basically it.
I would like to keep things clean, rather portable and flexible (can enable disable some tabs for example or add some easily).
Here are the questions :
1) How to have tabs "refreshed" when the database content changes ? Implement some Listener interface ? Should I define that interface or there is something already existing I can reuse ?
2) How to "link" the different tabs together so that it is easy to jump from one to another (and may have to carry some argument to setup the destination tab to the right "view")
3) If I set some preference with some filters in another part of the application, how do I share such settings with the whole application ?
And when I ask "how to", I really mean "what is the best way"... I can get that working already... just looking for the right tool to use, design pattern or such.
There are different strategies of gui application building. Here some article about.
If using swing, you can use tabbed pane to have a tabular layout.
Implement a listener (as you are planning). Have a look at observable interface in Java.
You can implement a singleton(eg PreferenceManager class) to hold the preference and access it across the application to access properties.
Do you really want a push model where the server has to maintain a connection to every client and then update them all when anything changes? This is feasible with a handful of clients, but quickly becomes problematic. It's probably better to use a pull model, where the client manually (periodically?) asks for updates. This is also a good way to use optimistic locking with a last_modified field in the DB. Attempt an update, if it's changed since you last reloaded, warn the user and allow them to overwrite / merge.
As for Swing in general, best practice is to factor everything out that's not GUI related into core classes ('business logic') that fire off events. Register all your Swing classes as the appropriate event listener and update the gui appropriately (SwingUtilities.invokeLater() is your friend here).
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/
The naive way of writing building a menu in a Java Swing app is to do something like:
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open...");
openItem.addActionListener(new ActionListener() { /* action listener stuff */ } )
fileMenu.addMenuItem(openItem);
A more experienced developer will recognize that actions can be accessed through a variety of mechanisms - menus, toolbar buttons, maybe even other workflows in the system. That person is more likely to write:
Action openAction = new AbstractAction();
openAction.setName("Open...");
openAction.addActionListener(new ActionListener() { /* action listener stuff */ } )
...
JMenuItem openItem = new JMenuItem(openAction);
My question is, what is the best way to manage these Action objects so they can be used across menus, toolbars, etc?
Create a factory class that returns specific actions?
Declare all of the actions as private static final Action in some utility class?
Take advantage of a Java application framework?
Something else?
Applications that I have developed that need to use that same actions across menus, toolbars, and other buttons have been done using Swing Application Framework.
Swing Application Framework
This framework will allow you to have a resource file where you can define all menu text, tooltips, and ICONS. I think the icons are the key, you do not have to load them yourself. Also, if you have any actions that you need to enable/disable you can override the method to control its state.
The website is worth the read.
You can group all your abstractAction using the dedicated Map javax.swing.actionmap .
See http://java.sun.com/javase/6/docs/api/javax/swing/ActionMap.html
Moreover each JComponent has an internal actionMap (getActionMap()).
class MyComponent
extends JPanel
{
public static final String ACTION_NAME1="my.action.1";
public MyComponent()
{
AbstractAction action= new AbstractAction() { ... }
getActionMap().put(ACTION_NAME1,action);
...
menu.add(getActionMap().get(ACTION_NAME1));
}
}
Hope it helps
Action is a bad abstraction - an ActionListener welded to a poor man's Map.
Certainly do not assign them to a static as they are mutable and also need some context to operate usefully.
My general advice for GUI programming is to note that it is actually much the same as any other area of programming. Follow the usual good practices. Notably, layering, separation of concerns, use (implementation) inheritance rarely and don't write a big ball of mud.
Also see this question, which is pretty much the same as what you're asking.
Create a base action for your application; this will help you IMMENSELY later on
Do create actions as you have in your code, instead favor subclasses of your base action
To organize them, it will depend on what you are doing with them, and you may have some actions organized one way and others created a different way. It will all depend.
What you want is to have a consistent way to locate/create an action in your code.
Depending on your UI, you may need to differentiate between "static" actions (i.e. stuff that's always available in your app, such as the menu system) and dynamic actions that are created only on certain screens or in certain locations.
In any case, using concrete subclasses of your specialized base action will help you keep these things organized. What you don't want is to be specifying things like labels, mnemonics, and icons all over the place in your code.
Edit: I got the feeling people didn't believe this was possible or easy, so I did it--took about an hour from scratch--would have taken 40 mins if I'd just used a single method as a target instead of reflecting it out to separate methods for each menu item.
Here's the Tested source code. It works, but is one big method and ugly--refactor it if you use it. I may fix it up a little over the next few days, I've always wanted to have a copy of this to keep around to reuse.
--- original post
First of all, remember to separate your code from data. That means you should NEVER type:
new Menu("File...");
The string "File..." is data. If you start thinking this way, you will find that your question answers itself.
First you need to build up some data. You need to get "File..." and "Save" into menus. I generally start off with a string array (which you can easily move to a file)
new String[]{"File...","+Save","Load"...}
This is one of the simpler patterns I've started out with. Then you can parse out the + sign and use it to mean "Drop down a level in the menu when you add this one"
This is just a silly convention, invent your own if you don't like it.
The next step is binding that to code to run. You could have them all call the same method, but what a pain in the ass (Giant switch statement). One possibility is to use reflection to bind a method name while you are reading in the data. Here's one solution (again it might not fit your tastes)
new String[]{"File...[fileMenu]","+Save[saveMenu]","Load[loadMenu]"...}
Then you parse out the thing in square braces, reflectively hook it up to a method in your current class and you are set.
There is a temptation I ALWAYS have at this point, and I've learned to fight it because it NEVER works out. The temptation is to use the first set of data ("File...") and manipulate it to fit some pattern and auomatically bind to your code (in this case, remove all non-alpha chars, make the first letter lower case and append "Menu" to get the correct method name). Feel free to try this, it's very attractive and seems slick, but be ready to abandon it when it doesn't meet some need (such as two menu items with the exact same name in different sub-menus).
Another way would be if your language supports closures, then you could actually create the file name and closure in the same place..
Anyway, once you start coding like this, you'll find that ALL your menu construction is in a single 10 line method and you can alter it to suit your needs. I had a case where I had to change a set of menus to a button hierarchy and I did it in 2 minutes.
In the end, you can use this pattern to set up the action objects easily and change how they are used easily (in a single location, single line of code), so you experiment with them. There are many ways to use them, but if you don't do what I'm recommending here, you will end up having to re-implement across every menu item for every change, which is really annoying--after a single change you will have wasted more time than if you had just implemented a data-driven solution in the first place.
This really isn't hard code, should take like an hour or two then you never have to write new Menu("... again. Trust me, this kind of tooling is just about always worth it.
edit:
I just about always code data-driven these days. Usually I'll prototype a few things the normal way, recognize the pattern and refactor--and if you are refactoring correctly, the data just about always factors out and what you're left with is beautiful, tight and maintainable.
I could do what I suggested above in less than 1/2 an hour (maybe an hour to do the reflective version). This is almost always just as long as it would do to use the unfactored version, and from then on, your savings multiply for every change.
This is very similar to what people like about ruby, except with ruby they seem to insert even more data into their code (which makes it awfully hard to extract your data from the code completely, which is always a nice goal for internationalization).
Hmm, did I mention that if you're good at extracting your data like this, i18n is virtually free?
I suggest you just give it a try sometime and see what you think. Embedding the control in the strings is unnecessary if it makes you uncomfortable. I tend to use string/object arrays just because they are really easy to enter, are still in the file while you are coding and are trivial to externalize later, but if you like YML or XML or properties files, use whatever you're comfortable with--just abstract your data from your code!