Java Swing without extending - java

I am trying to make my first 2D game in Java, and I am stuck at the very last thing.
I have already done all the logic in game, and so do I have a class named World which holds all the information about the world, makes turns.
The problem occurs when I am trying to implement some methods to show world in GUI - by that I mean: I have my parent class: World, and then I have child classes WorldGraphic, where i want to show a beautiful world, with images etc, and WorldStrategy where it is mentioned to show only the most important aspects(not so beautiful but much more 'clear' i would say), and I would like them to be swapped in UI.
And i have decided to choose Java Swing library to do it, but I have came across a big problem - I cannot inherit both World and JFrame(which was neccessary to do GUI in my swing guide), Is there any way to omit it?
My best idea so far was to make public function in my world that would output the data to print, but I have doubts about it effectiveness, I would like to keep it private(protected), and do it somehow on inheritance basis, as my GUI will also have some other options(probably I would have to make a lot public methods)
My question is more about how should the structure of my document look like(so the code is probably useless). As i have already mentioned I am fairly new to Java and I am not sure if it is correct to suddenly make every method public just so ONE of my classes(the GUI actually) could use them.

You have several questions in your one question, which is not fully allowed here, but regardless, let me try to approach the main ones
First of all, regarding the need to extend JFrame: This is absolutely not necessary and in fact, is usually not recommended. Much better is for you to use JFrames (and other GUI component) where needed, but not extend them unless necessary. Extend the component if you are extending its underlying behaviors, in other words if you're overriding a method such as a JPanel's protected void paintComponent(Graphics g) method.
Should WorldGraphic and WorldStrategy both extend World? I'm not sure that this is needed or desired. It sounds as if you're trying to separate your program's GUI portion, its "view", from its logic, the "model", and if so, both aspects do not need to and probably shouldn't extend from a parent class, but rather should be connected by a controller class.
Regarding, "As i have already mentioned I am fairly new to Java and I am not sure if it is correct to suddenly make every method public just so ONE of my classes(the GUI actually) could use them.": only make a method public if it is to be called by an outside class.
Of course, for a more detailed and concrete answer, you'll probably want to post your relevant minimal reproducible example code.

Related

What is the "usual way" to create a GUI for your application?

Hey guys I'm new to programing and I'm just gettin into UI design.
There are some things I've gotten so far, like I should only use a JFrame per application and other guidelines like that. What I don't understand is... what is the proper way to join your business logic with the GUI?
What I mean is, let's pretend I've just created an application that runs on console (or whatever), and I want to create a GUI for it, so, I've seen on the net that people create a JForm-derived class as a main class and that's it. But is this the proper way? I would like to keep my original "Main class" (the class that uses every other class I've created for my project) and define the form as a field of it, something like that.
Is it possible? If so, how can I achieve this? I have all my logic on that main class I just talked you about, so when I instantiate the form inside of it, I don't know how to make the form use and alter the fields and use the methods I defined in the main class (Sorry if I'm not making myself clear).
How you do, experienced people, do it? What is the "good practice" way? Thanks for taking your time and sorry if it's a noob question.
I'm no professional but I can't stand working with JFrames and Graphics objects.
Most of the time I use the lwjgl library. I know this library is for games but It is
great for UI's as well. The reason it is so easy is because you simply give buttons their
X and Y coordinates without having to worry about layouts. You can make your own images and
import them easily, so if you want your button to look like an image you created no problem.
Because it is made for games it is also very fast and fluid.
This may not be the best way but it works for me so I thought I would share anyway.
Hope it helps.
Here is the lwjgl website: http://www.lwjgl.org/
Here is a video series that helped get me started: http://www.youtube.com/watch?v=0v56I5UWrYY&feature=c4-overview-vl&list=PL19F2453814E0E315
Paranaix already mentioned in his comment about the model - view - controller architecture.
I mostly construct Java Swing GUI applications.
I build the model first. This could be considered a "first cut", since I update the model as I construct the view.
Next I build the view. I construct all of my Swing components by hand. I find that GUI builders harm more than they help. Building the view usually causes me to modify the model.
Finally I construct the controller.
Here's a more detailed description of how I put together a dice game from my blog.

Building the GUI from the constructor. [Design Decision]

I am just about done with our exam project, and when looking back at what I coded, I feel I did quite alright. Though, stuff could obviously always be alot better. But maybe that's just me.
I was in charge of coding the GUI, and coupling it with the application logic. When making the GUI I made the decision that I would make a class file for every window (e.g. LoginWnd.java), and actually build the GUI in the constructor. I would initalize everything and set all data inside this constructor.
Then in order to navigate through the application, I would set actionlisteners on the jbutton. For example, in SearchWnd, hitting the "Search" jbutton would create a new object of ResultWnd with some specified parameters.
Now i'm kinda wondering: Was this design decision bad in any way? Are there any design paradigms that I should've been aware of?
Thanks.
Your approach sounds fine overall - as long as it works you've achieved the main goal! So my comments here are more about fine-tuning / broader design aspects.
There's nothing fundamentally wrong with doing GUI construction in the constructor providing that the GUI doesn't subsequently change during program execution. The rationale here is that constructors should be reserved for "one-off" construction activities. So it's probably fine for dialog boxes and suchlike that have a pre-determined layout.
If you have a more dynamic GUI where components are frequently being added and removed throughout program execution, then I'd strongly suggest moving this to a set of methods outside the constructor so that they can be called independently of object construction. The constructor itself can still call these methods if needed to do initial setup, but subsequently you have the ability to call these methods later to add new components, refresh the layout etc.
The good news is that this stuff isn't hard to refactor if you get it wrong - it's usually trivial to pull setup code out of a constructor into separate methods later if needed.
Another thing to be aware of is the oft-repeated mantra "prefer composition to inheritance". That is to say, if you can make your GUI work by assembling existing components rather than inheriting and overriding your design will probably be better/more easy to maintain in the long run. For example, I don't think I've ever subclassed JFrame - it's almost always cleaner to just add JPanels within it that contain all the application-specific components.
Finally, be cautious of coupling your GUI components too closely to your application logic. Swing actually does a pretty good job of encoraging you to separate out your data model from the presentation code (e.g. with ListModel and friends). It's worth studying and understanding that approach. The point is that you should usually build GUI components in a way that is fairly application-agnostic, but give them application specific behaviour by connecting them to the right data model and event handlers etc.
I also initialize my GUI in the constructor, so it can't be bad :) But when it gets too long I extract parts of the code into separate GUI components.

How can I avoid passing around a single instance of a top level component to all my subclasses

So I've been trying to see how I could best structure my code, because I have an intuitive feel that there must be a better way to achieve what I want without passing around a single object to nearly every UI class in the project.
The project I'm working on has a class RhythmWheel that extends JRootPane. The constructor then goes on to create all the components that form a RhythmWheel. For example it creates an instance of ControlPanel (which extends JPanel) and adds it to itself.
However ControlsPanel needs to have a lot of knowelgde of things that are defined in RhythmWheels like the number of wheels that are currently selected. Currently the constructor for ControlsPanel takes a RhythmWheel as an argument, and then keeps a reference to it. It uses this for things ranging for component a JFileChooser should be parented to to, and as an argument to a function that writes the revelant state of the application to an XML file.
It seems wrong to me that I'm passing around a main component across so many classes. I thought about design patterns, and figured that a singleton might be a solution to this. However I have read numerous times that singletons are evil and are an anti-pattern. I guess the MVC pattern might help, but I'm not sure how I'd implement that in Swing. And most recently I came across Dependency Injection as a possible solution.
I'm a little lost as to what I should be doing, or if I should be doing aything at all. If you'd like to glance at the code I'm working on, you can see it at https://github.com/vamega/RhythmWheels so any advice on how to proceed would be great.
if everything needs a reference to RhythmWheel then it sounds like RhythmWheel is awfully complex. maybe you can break RhythmWheel into a collection of components that (hopefully, and likely, since GUI should reflect logical structure) correspond to particular parts of the GUI?
also, why do all the GUI components keep references to the RhythmWheel (or the appropriate sub-component, if you refactor as described above)? i haven't done much spring programming, but i thought the idea was to structure things round an observer pattern. in that case, the gui components should be registering themselves as observers on the wheel components, so that they can update when the wheel changes.
and yes, this is mvc. the wheel components form your model; the gui is your view. what is less clear is what the controller is. i suspect that it is the high-level wheel.
so, in summary:
the wheel is composed of sub-components
the wheel has high-level methods that reflect what you can "do" to it
the wheel's high-level methods are what are called by actions in the view
the wheel's high-level methods make changes to the wheel's sub-components
the wheel's sub-components, when they change, inform the model, which updates
only the input parts of the view need references to the wheel; the display parts are triggered via callbacks registered with the wheel sub-components.
(to answer the original question directly, i don't see anything so bad in passing around a wheel instance, but as i suggest above, it might be better for it to "fragment" into different components as it gets "lower" into the GUI).
I don't see what's wrong with using singletons. A control panel sounds like a prime candidate for a singleton. Why would have you more than one? Same goes for the others. Anything your currently accessing in ControlPanel from RhythmWheel can be exposed through getters and setters.
Unless there's a model/view separation that you would like to decouple or a view that needs to observe model updates, I wouldn't use MVC.

Questions: controlling a Swing GUI from an external class and separating logic from user interface

UPDATE: I'm using Netbeans and Matise and it's possible that it could be Matise causing the problems I describe below.
UPDATE 2: Thanks to those who offered constructive suggestions. After rewriting the code without Matise's help, the answer offered by ignis worked as he described. I'm still not sure how the code the Netbeans code generator interfered.
Though I've been programming in Java for awhile I've never done any GUI programming until now. I would like to control a certain part of my program externally (updating a jTextArea field with output from an external source) without requiring any user action to trigger the display of this output in the jTextArea.
Specifically, I want this output to begin displaying on startup and to start and stop depending on external conditions that have nothing to do with the GUI or what the user is doing. From what I understand so far you can trigger such events through action listeners, but these action listeners assume they are listening for user activity. If I must use action listeners, is there a way to trick the GUI into thinking user interaction has happened or is there a more straightforward way to achieve what I want to do?
Also, I'd really like to know more about best practices for separating GUI code from the application logic. From the docs I've come across, it seems that GUI development demands more of a messy integration of logic and user interface than, say, a web application where one can achieve complete separation. I'd be very interested in any leads in this area.
There is no need to use listeners. GUI objects are just like any other objects in the program, so actually
you can use the listener pattern in any part of the program, even if it is unrelated to the GUI
you can invoke methods of objects of the GUI whenever you want during the program execution, even if you do not attach any listeners to the objects in the GUI.
The main "rule" you must follow is that every method invocation performed on objects of the GUI must be run on the AWT Event Dispatch Thread (yes, that's true for Swing also).
http://download.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html
So you must wrap code accessing the GUI objects, into either
javax.swing.SwingUtilities.invokeLater( new Runnable() { ... } )
or
javax.swing.SwingUtilities.invokeAndWait( new Runnable() { ... } )
http://download.oracle.com/javase/6/docs/api/javax/swing/SwingUtilities.html
About "separating GUI code from the application logic": google "MVC" or "model view controller". This is the "standard" way of separating these things. It consists in making the GUI code (the "view") just a "facade" for the contents (the "model"). Another part of the application (the "controller") creates and invokes the model and the view as needed (it "controls" program execution, or it should do that, so it is named "controller"), and connects them with each other.
http://download.oracle.com/javase/tutorial/uiswing/components/model.html
For example, a JFoo class in the javax.swing package, that defines a Swing component, acts as the view for one or more FooModel class or interface defined either under javax.swing or one of its subpackages. You program will be the "controller" which instantiates the view and an implementation of the model properly (which may be one of the default implementations found under those packages I mentioned, or a custom implementation defined among your custom packages in the program).
http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/package-summary.html
That's a really good question, IMHO... one I asked a couple of years ago on Sun's Java Forums (now basically defunct, thanx to Oracle, the half-witted pack of febrile fiscal fascists).
On the front of bringing order to kaos that is your typical "first cut" of an GUI, Google for Swing MVC. The first article I read on the topic was JavaWorld's "MVC meets Swing". I got lucky, because it explains the PROBLEMS as well as proposes sane solutions (with examples). Read through it, and google yourself for "extended reading" and hit us with any specific questions arrising from that.
On the "simulated user activity" front you've got nothing to worry about really... you need only observe your external conditions, say you detect that a local-file has been updated (for instance) and in turn "raise" a notification to registered listener(s)... the only difference being that in this case you're implementing both the "talker" and the "listener". Swings Listener interface may be re-used for the messaging (or not, at your distretion). Nothing tricky here.
"Raising" an "event" is totally straight forward. Basically you'd just invoke the "EventHappened" method on each of the listeners which is currently registered. The only tricky bit is dealing with "multithreaded-ness" innate to all non-trivial Swing apps... otherwise they'd run like three-legged-dogs, coz the EDT (google it) is constantly off doing everything, instead of just painting and message brokering (i.e. what it was designed for). (As said earlier by Ignis) The SwingUtilies class exposes a couple of handy invoke methods for "raising events" on the EDT.
There's nothing really special about Swing apps... Swing just has a pretty steep learning curve, that's all, especially multithreading... a topic which I had previously avoided like the plague, as "too complicated for a humble brain like mine". Needless to say that turned out to be a baseless fear. Even an old idiot like myself can understand it... it just takes longer, that's all.
Cheers. Keith.
This doesn't exactly answer your question, but you might be interested in using Netbeans for Java GUI development. You can use GUI in Netbeans to do Java GUI development.
Here's a good place to get started -
http://netbeans.org/kb/trails/matisse.html

Java Design Questions - Class, Function, Access Modifiers

I am newbie to Java. I have some design questions.
Say I have a crawler application, that does the following:
1. Crawls a url and gets its content
2. Parses the contents
3. Displays the contents
How do you decide between implementing a function or a class?
-- Should the parser be a function of the crawler class, or should it be a class in itself, so it can be used by other applications as well?
-- If it should be a class, should it be protected or public class?
How do you decide between implementing a public or protected class?
-- If I had to create a class to generate stats from the parsed contents for eg, should that class be protected (so only the crawler class can access it) or should it be public?
Thanks
Ron
I think Andy's answer is very good. I have a few additions:
If you believe that a class will be extended in the future, you can set all your private methods (if any) to protected. In this way, any future extending classes can also access these.
I like the rule that a method shouldn't be longer than that you can see its opening and closing brackets ({ }) without scrolling. If a method is longer than that, try to split it up into several methods (private, protected or public by your preference). This makes code more readable, and could also save on lines of code.
So let's say a method is getting big and you split it up into several private methods. If these new methods are only used within the first "mother"-method, it makes sense to move all of that into a class of its own. In this way you will make the original class smaller and more readable. In addition, you will make the functionality of the new class easier to understand, as it is not mixed up with that of the original class.
The best guidance I've seen for these types of questions is the "SOLID Principles of OO Design."
http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod
The most basic of these principles, and the one that sort of answers your first question is the "Single Responsibility Principle." This states that, "a class should have one, and only one, reason to change." In other words, your classes should each do exactly one thing. If you end up needing to change how that one thing works, you only have one class to change, and hopefully just one place to make the change within that class. In your case, you would probably want a class to retrieve the content from the URL, another class to parse it into some sort of in-memory data structure, another class to process the data (if needed), and yet another class (or classes) to display the content in whatever format you need. Obviously, you can get carried away with classes, but it's typically easier to test a lot of small, single-operation classes, as opposed to one or two large, all-encompassing classes.
The question on public vs. protected depends on how you plan to use this code. If your class could be used independently outside your library, you could think about making it public, but if it accomplishes some task which is specific or tied to your other classes, it could probably be protected. For example, a class to retrieve content from a URL is a good general-purpose class, so you could make it public, but a class that does some specific type of manipulation of data might not be useful outside your library, so it can be protected. Overall, it's not always black and white, but ultimately, it's usually not a huge deal either way.
I like to think of classes as "guys" who can do specific stuff "methods".
In your case, theres a guy who can fetch the content of an url if you tell him which url that is.
Then there is this another guy, that is really good at parsing content. I think he does that with a tool called rome, but i'm not sure. he keeps that private (hint ;) )
Then we have that third guy, who displays stuff. He's a bit retarded and only understands stuff that "another guy" produces, but hey thats fine.
Finally the project needs a boss guy, who gives orders to the other 3 guys and passes messages between them.
ps: I never really though about making classes protected or not. Usually they are simply public without any specific reason. As long as it don't hurt, why bother?

Categories