How do I model a graphical application using UML? - java

I was taught UML early on in university but all the examples were always with simple console applications. Now that I have been assigned to develop a project with a graphical interface (using Java) and was required to submit a UML model, I haven't got a clue how to go about representing the graphical frontend aspect of the application in tandem with the non graphical backend classes. I'm not quite sure where to even start.
How would you suggest I go about doing this?

Usually UI modeling involves 3 things:
How the UI looks like: this is not usually done in UML. You need a tool like Visio or Pencil to do that.
How the UI is structured: This considers how the UI is structured into classes. How these classes are related to each other (dependencies, navigation, ...). How they are related to domain classes. How they are related to the Use Cases (which ones they implement). This fits naturally in UML structural diagrams: class diagram, package diagram, component diagram, ...
How the UI behaves in runtime: How certain actions cause objects to be created and methods to be called to perform the desired actions. This fits naturally in UML behavioral diagrams : sequence diagram, communication/collaboration diagram, activity diagram.
So basically in your UML model, UI classes (Screens, Applets, Pages, ...) will appear like normal classes. This will allow UI structure and behavior to fit in your application view models.
Note that there are tools that make use of UML profiles to provide UI mocking as alternative to graphical tools like Visio. In this custom profile you may find for example stereotyped class called << screen >> and stereotyped dependency called << navigation >> to model how UI elements trigger UI navigation to other screens.

I think you need to start by asking what you want to model and then that leads to you work out whether UML is useful and if so, which parts. Start by asking who is going to use this model and for what. Model with a purpose.
If you want to model the class structure of your application, then a UML class model might be useful. But even then, are you trying to illustrate the UI classes or the information (domain) structure, or both?
If you are trying to show how the runtime interactions work, then a sequence diagram might be useful.
If it is modularisation of code and dependencies between modules, a package diagram would do this.
If you have a complex user interface program with a sophisticated component structure which you want to explain, then it's no different to server software and a component diagram would be useful.
Whenever creating a model ask why you are doing it, for whom and what they want from it. That leads you to select something useful rather than just doing "busy work".

Asides from the previous answers, a common design for UI is one of model-view-controller (MVC). Some UML tools actually have stereotypes to help you with representing these elements. The model is the data that you want to show, the view is how it is displayed, and the controller links the two, taking the input to the UI and processing it to change the display with the new data from the model.
It is also easy and useful to create sequence diagrams for a MVC system to show the actions and their effects.

Related

UML diagrams + Android classes

I've been developing an Android app for a while but I didn't start with any particular diagram. And now comes the time to do some real diagrams but I don't know how. Not because I'm not familiar with UML but because of Android and it's components.
For example, my app requires that the user needs to be logged in in order to see a menu. From there the user can choose the options he wants. The user can also do his registration.
Although this might be a silly and simple example...The point is...I didn't use any class named "Person" with getters and setters; or any class named "Request" with getters and setters and other methods.
My app use classes like "Login.class", "SignIn.class", "MenuActivity.class", "HistoryActivity.class".
My question is...how do I use UML for an Android app?
I mean I can't have a conceptual model diagram that says "Person"-----"Request", right?
Thanks in advance.
I think you are confused with different types of UML diagram types,
There are,
Structural UML diagrams
Class diagram
Package diagram
Object diagram
Component diagram
Composite structure diagram
Deployment diagram
Behavioral UML diagrams
Activity diagram
Sequence diagram
Use case diagram
State diagram
Communication diagram
Interaction overview diagram
Timing diagram
And more, I think you are talking about Class diagram. Since class diagrams are technical and are targeted for the development team, It is totally fine to have all these Login.class, SignIn.class, MenuActivity.class, HistoryActivity.class in your class diagram.
But you can use conceptual things like Person, Request ect in your other UML diagrams (eg Use Case). because in these diagram this is targeted for many users not just developers, So using MenuActivity does not make any sense. Using conceptual entities is the way to go here.
Good luck
Your example suggests that you're trying to capture a some sort of use case. In this case you may need an activity diagram to demostrate the higher level view or a communication diagram if you're more concerned with more detailed one.
UML isn't concerned with programming languages, platforms and so on. Its main purpose is to provide a notation which can be used to communicate ideas without necessarily getting into too much details. So the first thing you need to consider is why you need diagrams in the first place and what you want to communicate with them. Given these questions answered it will become clear what kind of diagrams you need.
There is such thing as "4+1 model" which aims to separate the software model into several views. These views show different aspects of the software and concerned with different levels of detail. In Unified Process, for example, it is adviced to model from "top" to "bottom" of the solution, from high-level overview of use cases and main features to the actual implementation details. UML supports that providing different types of diagrams as well.
So if I understood I can use those conceptual terms (Person, Request) even if they aren't any classes with those names at all...they are used as an example right?
You indeed can, but not in diagrams with low-level features like Activities. You may want to build a domain class diagram that will include Persons and other entities relevant to your application, but won't be really represented in code.

Does the use of ObservableList in JavaFX go against Model-View-Controller separation?

I am attempting a study of JavaFX because I want to use it as the GUI of my program. My question is essentially a conceptual one:
To date my program is mostly the "Model" part of the MVC pattern; that is, almost all of my code is the OO-representation of abstractions in the sense of classes, and all of that code is logical code.
Since I do not want to be the only user of my program, I want to add the "View" part of MVC so that people can easily use and manipulate the "Model" part of my program. For this, I want to use JavaFX.
In my "Model" classes I obviously use various Lists, Maps, and other classes from the Java Collections API. In order to let the users of my program manipulate these underlying Lists and Maps I want to use the Observable(List/Map) interfaces in JavaFX.
A concrete example to bring clarity to the situation:
Let's say that I have a MachineMonitor class that every 3 minutes checks certain properties of a Machine, such as if the connection is still good, the speed that the gears are turning, etc. If certain inequalities are met (say that the speed of the gears has fallen to a rate of 1 turn/sec) the MachineMonitor fires a RestartMachineEvent.
Currently I use an ArrayList<MachineMonitor> to keep track of all of the individual MachineMonitor's. Now extending to the "View" part of MVC, I want the User to be able to manipulate a TableView that displays the list of MachineMonitors so that they can, for instance, create and remove new MachineMonitor's to monitor various Machines.
So that I can keep track of what the user of my program wants to do (say, create a MachineMonitor for Machine #5 that checks to see if the turn/sec of the gears falls below 0.5) I use an ObservableList<MachineMonitor> as the underlying List for the TableView.
The easiest way to link the "Model" and "View" of my program would simply be to change the "Model" class to have an ObservableList<MachineMonitor> and not an ArrayList<MachineMonitor> but (getting to the topic of the question) I feel that this is very messy because it mixes "Model" and "View" code.
A naïve approach would be to use an ObservableList<MachineMonitor> for the TableView and retain the use of my ArrayList<MachineMonitor>. However, changes made to the ObservableList<MachineMonitor> do not affect the underlying List as per the JavaFX specifications.
Given this, is the best way to solve this conundrum to make a ChangeListener for the ObservableList<MachineMonitor> that "propagates" the changes made to the ObservableList<MachineMonitor> to the underlying "Model" ArrayList<MachineMonitor>? Perhaps put this in a class called MachineMonitorController?
This ad-hoc solution seems very messy and non-ideal.
My question is: What is the best way to retain nearly complete separation between the "Model" and "View" in this scenario?
Briefly, I don't think use of ObservableList breaks the MVC contract.
The rest, you may read or not as you wish, as it is quite annoyingly long.
Architectural Pattern Background
Observables are useful in MVC style architectures because they provide a way of feeding data back and forth between the MVC components through loose couplings where the model and view classes don't need to refer directly to each other, but can instead work with some shared data model which communicates data flow. It's not a coincidence that the Observable pattern and the MVC style architecture concept both originated around the same time at Xerox PARC - the things are linked.
As noted in Martin Fowler's GUI architectures, there are numerous different approaches to building GUIs. MVC is just one of these, kind of the granddaddy of them all. It is nice to understand MVC well (it is often misunderstood) and MVC concepts are applicable in many places. For your application you should use the system which feels best for you rather than rigidly following a given pattern (unless you are using a particular framework which enforces a given pattern) and also be open to adopting different patterns within an application rather than trying to shoehorn everything into a single conceptual framework.
Java Beans are a fundamental part of almost all Java programs. Though traditionally often only used in client apps, the observer pattern, through PropertyChangeListeners, has been, for good reason, a part of the Java Bean specification since it was created. The observable and binding elements of JavaFX are a rework of that earlier work, learning from it to build something that is both more convenient to work with and easier to understand. Perhaps, if the JavaFX observable and binding elements had existed ten or twelve years ago as part of the JDK, such concepts would be more generally used in a wider variety of libraries and frameworks than a couple of pure GUI frameworks.
Advice
I suggest considering the MVVM model and other GUI architectures.
If you want a dead-easy framework which follows a model, view, presenter style, definitely give afterburner.fx a spin.
I think the correct choice of architecture depends on your application, your experience and the size and complexity of the problems you are trying to solve. For instance, if you have a distributed system, then you could follow REST principles rather than (or in addition to) MVC. Whichever you choose, the architecture should aid you in solving the problem at hand (and possibly future problems) and not the converse. Over-architecting a solution is a common trap and is very easy to do, so try to avoid it.
Caveat
One caveat to consider is that observables necessarily work via side-effects which can be difficult to reason about and can be antithetical to the concept of isolation. JavaFX features some good tools, such as ReadOnlyObjectWrapper and ReadOnlyListWrapper, to help limit the impact (damage control if you like) on observables so they don't run amok in your system. Use such tools (and immutable objects) with reckless abandon.
Learn from Examples
For a simple JavaFX application which is built using observables, refer to tic-tac-toe.
For a good way to structure a large and complex JavaFX application with FXML based components, refer to the source code for SceneBuilder and SceneBuilderKit. The source code is available in the JavaFX mercurial source tree, just check it out and start learning.
Read up on the JavaFX UI controls architecture. Examine the JavaFX controls source code (e.g. Button and ButtonSkin or ListView and ListViewSkin) to see how concepts such as MVC can be applied using JavaFX structures. Based on that learning, try creating some of your own custom controls using the architecture that the JavaFX controls framework provides. Often, when you are building your own application you don't need to create your own controls (at least ones which derive form JavaFX Control). The JavaFX Controls architecture is specially crafted to support building libraries of reusable controls, so it is not necessarily generally suitable for all purposes; instead it provides a concrete demonstration of one proven way to get certain things done. Adopting and adapting proven solutions goes a long way to ensuring you don't reinvent stuff needlessly and allows you to build on a solid base and learn from the trials of others.
Regarding your Concrete Example
I advise you to go with:
The easiest way to link the "Model" and "View" of my program would simply be to change the "Model" class to have an ObservableList and not an ArrayList
Maybe use a ReadOnlyListWrapper to expose the ObservableList from the MachineMonitor to the outside world, so that nothing can modify it unduly.
Setup some other structure which encapsulates the view (for example a ControlPanel and ControlPanelSkin) and provide it a reference to the read only observable list of MachineMonitors. The ControlPanelSkin can encapsulate a TableView, a graph or whatever visual knobs and widgets you want to use for the user to monitor the machines.
Using such a structure effectively isolates your view from the model. The model really doesn't know anything about the UI at all and ControlPanelSkin implementation could be changed out to a completely different visual representation or technology without changing the core MachineMonitor system at all.
The above just outlines a general approach, you'll need to tweak it for your specific example.
I disagree that using an ObservableList in your "model" class violates MVC separation. An ObservableList is purely data representation; it is part of the model and not part of the view. I (and others) use JavaFX properties and collections in model representations in all tiers of my applications. Among other things in there, I point out how I use JavaFX properties that are (or can be, at least) bound to JSF. (I should mention that not everyone agrees with the approach of using FX properties on the server side; however I don't really see any way to make the argument that they are somehow part of the view.)
Also, if you do
List<MachineMonitor> myNonObservableList = ... ;
ObservableList<MachineMonitor> myObservableList = FXCollections.observableList(myNonObservableList);
myObservableList.add(new MachineMonitor());
the observable list is backed by the non-observable list, so the change occurs in myNonObservableList too. So you can use this approach if you prefer.

how is a user interface usually built?

I have four classes flight, passenger, seating chart, and waiting list. I'm trying to create a gui. I am new to swing so I dont know how it is done. should I create a separate class for a gui and build all the gui there or should I incorporate my gui code in those already existing classes? how is it implemented if there is a general guideline?
The classes that you mention are model classes; they are used to abstract the data of your system. You should never put your presentation [GUI] code in model classes. You must have separate classes/code for your presentation[GUI].
The general guideline is that :
Separate Presentation, Controller and
Model code into different classes. Use
the model-view-controller design
pattern for your system.
In all programming languages is nice to separate UI and code. It's better to understand and keeps you code clean.

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.

GUI guidelines for swing

Is there a resource where GUI design for swing is explained? Like best practices and such.
Design guidelines aren't exactly followed much anymore because Swing works on so many different platforms. Sun wrote up some a long time ago, and never changed them so I'd say read it if you think it will help. Here is some practical knowledge about doing swing development.
Never use GridBagLayout. Grab TableLayout. It radically simplifies layout for you Swing UI. GridBagLayout is the devil.
Don't over embed components just to get a layout right (i.e. embedded BoxLayout, etc). See point 1 for how to do this. There are performance issues having components on the screen.
Separate your program along MVC lines. Swing has View and Model separation, but in large programs the View (i.e. what subclasses a Swing Component) turns into a psuedo View/Controller only making things complicated to reuse and maintain. It turns into spaghetti code fast. Break the habit and create a Controller class that DOES NOT extend Swing. Same goes for the Model (no swing). Controller instantiates high level view classes, and wires itself as a listener to views.
Simplify popup dialogs using simple panels only. Don't subclass JDialog. Create a reusable dialog class that wraps a panel that can be used something like JOptionPane. Your panels will not be tied to dialogs only and can be reused. It's very easy when you work this way.
Avoid actionlistener/command. This is old junk and not very reusable. Use AbstractAction (anon classes are your choice I don't have a problem with them). AbstractAction encapsulates text, icon, mneumonics, accelerators, reusable in buttons, popups, menus, handles toggling enabled/disabled states, can be shared among multiple components, it also is the basis for InputMap/ActionMaps for mapping keyboard strokes to actions. ActionMaps give you loads of power for reuse.
It's best to have to view dispatch events to the controller. I'm not talking about mouse/keyboard junk, but high level events. Like NewUserEvent, AddUserEvent, DeleteUserEvent, etc. Have your controller listen for these high-level business events. This will promote encapsulation by keeping the concerns of the view (should I use a table, list, tree, or something else?) separated from the flow of the application. The controller doesn't care if the user clicked a button, menu, or checkbox.
Events are not just for the Controller. Swing is event programming. Your model will be doing things off the SwingThread or in the background. Dispatching events back to the controller is a very easy way to have it respond to things going on in the model layer that might be using threads to do work.
Understand Swing's Threading rules! You'd be surprised how few people actually understand that Swing is single threaded and what that means for multi-threaded applications.
Understand what SwingUtilities.invokeLater() does.
Never* ever use SwingUtilities.invokeAndWait(). You're doing it wrong. Don't try and write synchronous code in event programming. (* There are some corner cases where invokeAndWait() is acceptable, but 99% of the time you don't need invokeAndWait() ).
If you're starting a fresh project from scratch skip Swing. It's old, and it's over. Sun never really cared for the client like it did the server. Swing has been maintained poorly and not much progress has taken place since it was first written. JavaFX is not yet there, and suffers from lots of Swing's sins. I'd say look at Apache Pivot. Lots of new ideas and better design and an active community.
I have written a list of recommendations here.
In larger swing projects I do partinioning of the app like that:
Have one class per GUI element like JPanel,JDialog etc.
Use a separate package for each screen, especially if you have to implement customized TableModels or other complex data structures
Don't use anonymous and inner classes, implement instead an ActionListener and check ActionEvent.getActionCommand() in there.
EDIT: If you're rather looking for a tutorial or introduction you could start here
Maybe not exactly what your looking for but it won't hurt to take a peek at Java Look and Feel Design Guidelines
You can check the ideas behind FEST - a swing testing framework. It's main site is here and the project is hosted here
You can find some of best practices in chapter 4 of Professional Java JDK6 Edition
I have some guidelines too:
1) Use Maven and seperate your application into modules (view, controller, service, persistence, utils, model). Be sure you put your Swing components and dependencies only in view package, so if you want to change view framework some day, you can just reimplement view module but you can leave your business logic, controllers, etc... intact.
2) Use GridBagLayout because its very flexible and most configurable
3) Use a SwingTemplate (i can give you an example if you want)
4) Create a SwingFactory that creates components so you can reduces the amount of lines of codes since JFrames orso intend to be very large classes...
5) Let the view (JFrame, JDialog, etc...) have a dependency on controllers. Only do validation input on JFrames but then pass parameters to controllers. They will decide which business logic (service, processors, etc...) will be triggered.
6) Use lots of enumerations
7) Always think how your application can change or how it can be maintained. Therefore, use always code against interfaces or abstract classes. (Think abstract)
8) Use design patterns in your application because they provide confort and maintainability of your code. Make for instance all your controllers, services, dao's singleton classes. Make factories (swingfactory, ...) so you have to write less code over and over again.... Use observers so actions can be processed automatically.
9) Test your appliction: Make a choice between: TDD (Test Driven Design) or DDT (Design Driven Testing)
10) Never put any business logic on JFrames, because it is ugly and its not very Model-View-Controller design. JFrames are not interrested on how the data has been processed.
Hope that helps.

Categories