GUI structure organise [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How would one best organise his GUI. I have a JFrame which will hold my application. Currently I have put all JPanel, JTables and others which will fill up the JFRame inside the custom JFrame class.
I instantiate these components there and save them in a local field. Would it be a better practice as to make a seperate class for each JPanel,JTable and use getters and setters to manipulate the objects?
For example. My current GUI class is about 3500 lines long which gets more complicated over time.
Thanks in advance.
EDIT (he wanted screenie):

I would definitely suggest you start to separate your GUI components into different files, it will help in the long run. As far as best practice goes, I think it is better than cluttering a file with multiple classes even if they are related to each other. The only benefit I can see is you have only 1 file to open to see all the GUI code.
As you said, having a long class (3500ish lines) can make it troublesome to maintain. Organize them in proper packages too while at it. Like making a gui package, or whatever name you feel is appropriate, and so on.
Good advices are given in the answers of the questions tagged user-interface and organization

Break up your GUI code into custom panels.
ie:
class MyPanel extends JPanel { .. }
You should be able to break up the frame into logically distinct panels.
For a busy frame maybe I would have three custom panels. But this can drastically vary depending on what you have.
Also have a controller class. The controller handles backend calls to delegates, and event listening. Your GUI classes, eg customer panels, or custom frame should contain barely any if or loop statements. All that kind of logic should be in your controller.

More complex GUI code is usually generated by an IDE and not hand-coded. Sometimes, you might edit the generated code to get certain effects, but for very complex setups it becomes overly burdensome to hand-write the Swing code. Better to use a tool to generate it for you.
If you already have 3,500 lines of code, it's probably time for you to consider a GUI builder to take some of this work away from you. The learning curve can be steep, and it's not the easiest thing to do, but I would suggest it's way easier than hand-modification of a large GUI.
So basically, the answer is that for moderate/complex GUIs, people don't usually do it the way that you're doing it.

Related

Draw sequence diagrams for a Java Swing application [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 days ago.
The community is reviewing whether to reopen this question as of yesterday.
Improve this question
I have a simple ATM system implemented in Java using Swing (I know Swing isn't really used anymore but I wanted it to be simple). The way I implemented it is as follows:
I have a Customer class which holds information about a customer and has a login() method
I have an Account class which holds information about an account and has methods for withdrawing, depositing and transferring money
I have a Transaction class which holds information about a transaction and has a generateReceipt() method that creates and exports a PDF with transaction info
I have an ATM class which holds the logged in account and the corresponding customer and has static methods for getting transactions, such as the current account transactions
Finally, I have an Admin class with username and password as attributes and methods for getting all the customers and accounts, adding a customer or creating an account and deleting a customer or an account.
My application uses a MySQL database for storing information and making updates. Also, customers can have multiple accounts and one can log in the system using the account number and PIN.
I drew the use case diagrams, and the class diagram, not considering my UI in the class diagram.
I have a hard time creating sequence diagrams for this application, as all my classes and objects are used in classes made with Swing.
My question is: how should I structure my sequence diagrams, considering the fact that it is a Swing application? Should I add the UI classes or should I make it more conceptual and only describe the process and relations between my other 5 classes?
Any help is highly appreciated!
I tried separating as much logic from the actual UI, but I still can't figure out how should my sequence diagrams look, as a customer and the admin interacts with the Swing frames.
The class diagram without any of the app's internals is a "domain model". Its goal is not to document all possible classes used in your apps, but to focus on the domain knowledge, independently of how the app is implemented. The diagram would stay the same if you had a real ATM device, if you would implement a web service, or if you would use any other UI framework.
So you made a clear choice on what you wanted the diagram to show. You could perfectly have chosen to have monstrous class diagram including in addition the classes required for the business logic, for database interaction and for the UI (e.g. using the famous Entity Boundary Control pattern). The diagram would then be more dependent on your implementation choices.
For the sequence diagram, it's the same. There is no best way to draft this diagram. The question is only about what you want this diagram to focus on: do you want to model the domain logic ? In this case you would use your domain classes and show how they interact. Or do you want to model the detailed application design , in which case you could envisage to add also UI classes. But the diagrams would then quickly become very complex, and you'd better break them down into several simpler SDs, each focusing on some parts of your detailed technical design.

List of GUI functions built in NetBeans? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I am using the drag-and-drop style of GUI ( I can't write GUI code yet ).
I only know a few function like: setVisible, getText, setText, etc.
But I want to learn all the functions for the buttons or textfields that I can use
If you mean the Swing GUI:
The actual methods you can call and fields you can access in your code are exactly what you'll find in javax.swing in the Java documentation corresponding to the class you're looking at.
For example, if you have a JFrame, you can find all the methods in javax.swing.JFrame.
Properties are derived from the above Swing methods (mostly in a "remove the 'set' and 'get' manner").
For example, if you have a JFrame, you might see a background property in Netbeans, and you can find setBackground and getBackground in the documentation.
Bindings seem to be NetBeans specific, but these are also based on the properties.
For example, there's a background binding and also a background property.
Events are a bit more complicated - for example, all the mouseX events correspond roughly to addMouseListener and addMouseMotionListener, where the corresponding MouseListener and MouseMotionListener parameters has the mouseClicked, mouseEntered, etc. methods.
If you mean AWT, I imagine something similar would apply for that (but just taken from the java.awt package instead).
That's not to say every method appears in some form in the NetBeans UI - it wouldn't make sense for something like update to appear there, since that's something you need to decide when to call yourself during runtime.
Whenever you intend to study all the methods of a class, the first thing to check should be the documentation entry of that class (if exists). In general, it should contain some of the methods you are interested about and looking at the documentation entry of the parent class and the parent class of the parent class and so on should reveal all the knowledge you are interested about, therefore, this could be the learning algorithm:
define a set of classes you intend to study
open the documentation of the class
add the parent class/interface to the list described in step 1
create a list of methods you are interested about (probably you are not interested in all of them in all the cases)
go through the methods one by one
reread your lists and check whether you think there are items you might not be remembering some important details and if there are so, reread their entry. Repeat this step until there are no such items
If you already have satisfying theoretical knowledge, but you are not sure about the practice, you might want to create some small sandbox projects to try the things you just learned.

BestPractices: Is it bad OOP to subclass standard classes into a new one that does same thing, but "presuming" future changes? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have had similar cases in the past, and this is just an example to illustrate:
I'm going to implement a new feature in my android app (but this applies to any kind of OO project), and at this point I need to implement some "action" in the "setVisibility" method from EVERY edittext in EVERY activity I have.
To do it, I have to subclass "EditView", and override "setVisibity" method:
#Override
public void setVisibility(int visibility)
{
super.setVisibility(visibility);
// --> do my stuff here! <--
}
So far, so good... the problem is to change all activities I have (more than 200, and thounsands code lines), and then I think: "why on earth didn't I start the project subclassing the standard EditText, 'cos I knew some point I'll need to implement something like this".
That's the point: Is it bad OOP to subclass a "standard class" into a new one that does exaclty same thing, but just "presuming" cases like that? I mean, subclass everything, like buttons, activities, etc.
AFAIK, desing pattern and OOP discourage the "presuming factor", but I'd to hear what you guys "do in real life" (or think about that), based on your programming experience.
Also, maybe this type of question ("what you think", "what your oppinion") isn't a good practice here in SO, but I can't find any better place to put it on.
There's no reason to stub out code unless you're actually making changes. It's wasted effort, and just bloats your codebase.
If you find yourself in a situation where you're repeatedly making the same modification, consider refactoring to share common code. Or in certain cases, there's merit to generating those pieces of code (for example, Avro does this).
No, it's not bad, and I recommend you always do it on any class you'll reasonably extend over time. For example in our iOS projects we always start with a UIViewController subclass called ViewControllerBase that does nothing but extend Apple's base class (the same can be said for Activity on Android).
When we need to add something in later that should apply to every view controller (analytics perhaps), it's easy to do.
Fortunately, even if you have a lot of classes in your code it's easy to inject your custom base class with a simple search and replace across your codebase.
Do be careful though as once you have a class that's in everything, small changes can of course have broad and possibly unexpected effects. Be sure to test thoroughly!
EDIT:
Regarding subclassing everything, I'd say no. You quickly reach a point of diminishing returns on your time and utility. A common view controller base is pretty standard, as for buttons and so on probably not so much. It depends entirely on what you want to do that you think might need custom functionality. If you want to log every user action, then maybe you do want to subclass every control, but in that case it might be better to just log touch events. At the end of the day though, are you really going to parse all the data that gets generated? Probably not. So make sure you have a solid use case before you go crazy subclassing.
In my opinion there are some cases in which it makes sense to derive classes of a Framework.
At work we used derived classes for the UI-Elements to have control over their behavior.

An own class for everything [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm making a customer administration software. There are several JPanels with much content on it, constantly communicating with a database. In the database is customer data, products etc.
For a faster access to the database data, at first I load it all in its own ArrayList, e.g. ArrayList<Customer>. If the user changes this data, it has to be changed in both the class and the database.
As the JPanel View looks very "full" (crammed with other JPanels and JTabbedPanes, switching through with the CardLayout), I thought it would be better to create an own class for every "main" JPanel and link them all with View.
For example an own class for the JPanel Customer, where all the customer data can be seen and edited, the same for products etc.
Does is make sense or is it inconvinient? I only want to do so to outsource the code and to make the classes clearer, especially View.
Is there something like a design pattern dealing with this problem?
So your program consists of a single class that subclasses JPanel and that contains references to all other components used in your UI? And you want to know if you should break out portions of that UI into other classes.
In short YES. You can always decompose any class into aggregated classes by moving portions of that code out into a new class, and have the original class contain a reference to the new class. This is called delegation or Extract Class refactor. You can read about this technique in Martin Fowler's Refactoring book.
Creating other UIs that are parts of the total UI, like CustomerPanel, is a good way to think about it. By doing this you can also decouple parts of your UI. Be careful when you create these smaller classes to move all dependencies to the new class. If you feel like passing a reference back to the main UI to the aggregated class then you probably haven't fully decoupled your classes. That should be a sign either you haven't given enough responsibility to the class you are extracting, or there is some other dependency they should be sharing.
Basically the rule is if you extract a class, it shouldn't have a reference back to the class that contains it. References should be more of a tree than a graph. It's ok for them to share a model class, but its not ok to create cycles between views.
You probably would find this interesting:
GUI guidelines for swing
I am not sure if I understood your intent, but looks like you want to achieve the level of decomposition which will allow you to outsource certain UI components and reuse them, well, basically achieve as lower coupling as possible. Apart from what #chubbard said, I would suggest you to look into MVP pattern and use event-based interaction between components rather than referencing them. This can eliminate unwanted dependencies and bring more reusability.

How do you structure a java program? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
For quite awhile I have been trying to make a simple "game" in Java that is really just an applet with a square and a grid. What I want it to do in the end is the user clicks and the square will move to where the user clicked rounded to the nearest grid square.
The problem is I am a self taught beginner and I am having a hard time figuring out how to actually structure the program, some examples:
should I have a separate class listening for mouse clicks?
When I receive a click should I send it to some other object that represents the box and let it decide what it wants to do or just call some function that makes the box move?
I really want to learn all this "when to use what" stuff for myself so any links or general advice is appreciated.
What you're really asking is how to develop a game, which is notably different from a typical Java application. However, I'll give you a few ideas to at least point you in the right direction.
Take advantage of the fact that Java is an object-oriented language. That is, objects should each have their own responsibility.
Separate your game into three key layers: the application layer, the game logic layer, and the presentation layer.
The application layer should contain all of your helpers and generic subsystems, things like random number generators, text parsers, file access modules, mesh loaders, etc.
The game logic layer should implement all of the rules of your game, and be responsible for maintaining canonical state. Basically, when you press the "W" on the keyboard to move forward, the game logic layer should receive MOVE_FORWARD_REQUEST from the UI.
The presentation layer should be responsible for two things: getting input, and rendering your world. When it gets input, like the "W" key, it should map that to an action, and send that to the game logic layer to be processed. Then, it should render the world based on whatever the game logic told it to do.
Game development is obviously an entire realm with many books dedicated to it. One of my favorites is Game Coding Complete, which does focus on C/C++, but should give you a good idea about how you ought to structure your game.
Good luck!
One main principle of good software development is the Single Responsibility Priciple. It states that a function or class should only have one responsibility.
This way your classes and objects shouldn't become too big and unmanageable.
I think one of the most important concepts to master when developing software is the concept or Orthogonality. It's not the simplest definition, but in essence it means that one component (such as reading mouse clicks) shouldn't be directly tied to an unrelated component (moving a square on the screen).
In your case, the code reading mouse clicks should be separate from the code that actually moves the box. Whether you implement this as inner/anonymous classes or not is up to you. But if you follow the Orthogonality principle, it will be easy to change at a later date should you change your mind.
One problem here is that all the rules have some leeway in them where you have to use your own best judgement.
For example, the app you are describing now seems to me so simple I'd probably do it in a single class, with perhaps a couple of nested, perhaps anonymous classes. In any event, I could make a decent case for fitting the whole thing into a single source file, claiming that multiple source files would actually increase the complexity of the whole thing.
But if your GUI had a number of different controls, perhaps each controlling different behavior, it would become time to split the functionality up so you're not ending up with a big bowl of spaghetti code.
The Java GUI libraries try to naturally separate (view+controller) from model. You are encouraged to define and display the GUI in one module (= file) but to have your data model and perhaps functionality in another. For complicated GUIs, there may also be multiple GUI implementation modules held together by code.
One way to keep things "clean" is to work in "layers" where each layer "knows" only what it needs to know. To be specific, the GUI layer needs to know about the existence of its underlying models – tables and lists and whatnot need to be connected to TableModels and ListModels, etc. It doesn't need to know about details of these models though, so it can simply refer to those models by interface.
The model layer, on the other hand, need know nothing about the GUI. The less it knows, the better, and this would theoretically enable you to exchange GUIs without needing to touch the models.
My model can also contain ActionListeners to respond to actions undertaken by e.g. pushing buttons in the GUI.
Of course, actions and changes to the model will often result in changes to the GUI. How to communicate these changes to the GUI if the model layer doesn't know about the GUI? You can use bound bean properties here. Here's a short tutorial: http://www.javalobby.org/java/forums/t19476.html . So you have the same kind of structure: Changes happen in your model, they're communicated to beans with property change support within the model, and the GUI can attach listeners to those properties to find out something changed.
Whether you perform actual, effective actions (e.g. writing files, converting data, whatever) within your model code or whether you split "processing" code off into yet another module is up to you and will again depend on how cluttered your model already is. If there's a tiny handful of fields and methods feeling lonely in there, you may decide to mash things together but the moment it starts to look messy you'll want to refactor your processing code out into its own module. Processing sounds like the kind of module that doesn't want to know about other modules either; you may end up just calling its methods from the model level.
I've described my basic style for doing GUI development. There are certainly other recommendations out there, and you will likely develop your own style based on your experience. This is just intended to give you an idea and a possible starting point.
Step 1 - find the demo applets supplied by Sun. http://java.sun.com/applets/jdk/
Step 2 - read those demo applets. At least three. Preferably all of them.
One you've read several applets, you should see a little more clearly how to organize programs. You can then ask questions with a lot more focus pointing to specific applet examples and your specific programming problem.
Yeah, I'm a beginner programmer myself. Yeah, segregating functionality across multiple classes is a good way to reduce complexity and increase cohesion of individual classes.
Increasing cohesion good because by having more complex data structure your algorithms become less complex and your code is less dependent on each other.
For instance in your case it might be a good idea to separate the classes in accordance to MVC (Model View Controler).
You have a Model which represents the way your game data is structured.
You have a Viewer which present your Model in what ever form you please.
Have a Controller which picks up changes in the Model (via Listeners) and then updates the Viewer
Now you can change your Model and add extra functionality requiring only small changes in the way the Viewer works.
There are many Patterns out there but there isn't a hard rule when to use one over the other. There are some cases in which you can use several and there are cases in which will require you to chose one design pattern over the other.
Every beginning Java programmer should start with the Sun Tutorials. They are quite good.
Another good source, especially among free sources, is Bruce Eckel's "Thinking in Java", available from http://www.mindview.net/Books/TIJ/.
But the latter is a little dated compared to the former. That is why I recommend both.

Categories