File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Swing / AWT / SWT and the fly likes First GUI program Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "First GUI program" Watch "First GUI program" New topic
Author

First GUI program

Manny Ruiz
Ranch Hand

Joined: Dec 01, 2010
Posts: 40
I am currently taking a class where our first assignment is to create a mortgage calculator program which will display payment amount for loans in which the user enters the loan amount, rate, and term using a GUI. I started the program by defining the variables, importing the scanner, and making the calculations. Everything works fine, but there is no GUI. Now my question is is this a good way to start? Or should I create the GUI first and then work on the calculations afterwards. Is there an easy way to create a GUI and just add the calcualtions to it? I have been reading the material, but I am still confused by GUI.
Jonathan Johansen
Greenhorn

Joined: Aug 04, 2009
Posts: 8
I think you need to be more specific, you say you need a GUI. What exactly do you need? You need buttons, fields or what.
Also I think that in order to get help, you need to provide some sort of an attempt.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14338
    
  22

Here is a good tutorial on creating a GUI for a desktop application, using Swing: Creating a GUI With JFC/Swing

I'd create the logic for the program first, make sure it works correctly, and then after that create a GUI that calls that logic to do the calculations. It's a good idea to keep the GUI code separate from the main program logic - don't put the logic in the GUI code (for example, in onclick handlers for buttons) - if you do that in a larger application, it quickly becomes a big ball of spaghetti code without any organisation.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Greg Brannon
Bartender

Joined: Oct 24, 2010
Posts: 563
You've stumbled onto the idea of separating the parts of a GUI program into the logic and the GUI, also known as the model and the view. Taking it a step further is to add a third element to arbitrate the interaction between the model and the view known as the controller. Put the three elements together, and you have Model-View-Controller, or MVC.

Implementing this approach may be advanced for the course you're taking, but it's never too early to learn about and incorporate good habits. If you'd like to know more about the MVC approach, I found the tutorial in the link below to be a good intro to the topic.

Building a GUI using the MVC architecture


Always learning Java, currently using Eclipse on Fedora.
Linux user#: 501795
Manny Ruiz
Ranch Hand

Joined: Dec 01, 2010
Posts: 40
Thanks for the help so far, those links explained some, and I actually installed netbeans and created a simple jframe object, but now I' m stuck figuring out what do do next. SO i decided to try to create a simple addition program. Here it is. Am I on the right track and ready to start creating the GUI, and if so what is the best way to do it, by created a new class, or a new method for the GUI? On the GUI i want to have a text box labeled "num 1" and another "num 2" a button to "add" and a text box labeled and answer.

Greg Brannon
Bartender

Joined: Oct 24, 2010
Posts: 563
You say you created a simple JFrame object. What did you do with it, where is it? Show us what you've gotten from the links you read and what you've done with that new knowledge.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14338
    
  22

NetBeans has a very nice GUI builder, with which you can graphically design your GUI, by dragging and dropping elements such as text boxes, buttons etc. onto your JFrame. You can then add code to your buttons, that gets executed when you click the button.

Have a look at this quickstart tutorial for NetBeans, with links at the bottom to more tutorials: Designing a Swing GUI in NetBeans IDE
Manny Ruiz
Ranch Hand

Joined: Dec 01, 2010
Posts: 40
I have done the GUI yet, i was only stating that I was messing around with netbeans and created a jframe, but not the one for this project. I was lloking for feeback to see if what I have done so far looks like it is on the right track. In the class I just finished we were never given feedback on our projects, so i have always done all my work in the main method, I know this isnt ideal ,but i dont have anything else to go by. I am currently working through the netbeans GUI tutorial, thanks for that link
Greg Brannon
Bartender

Joined: Oct 24, 2010
Posts: 563
Your logic is on the right track, IF you want to do everything from the terminal, contrary to your stated objective. In your new GUI program, little will be done in the main() method. There are many options, but the general concept will be similar to:

A class that creates the GUI (or the view)
- the view will contain the code to draw the user interface
I suggest that your GUI will be a JFrame with a JPanel to which the Swing components are added, minimally:
- 2 editable text areas for data entry (the addends will be entered here, rather than from the terminal)
- 1 non-editable text area to show the solution (the solution will be displayed here, rather than at the terminal)
- a button to command the addition
- JLabels to label the text areas
- getters and setters as necessary to relay the user's inputs and to show the model's output

A class that performs the model function
- contains the program data
- contains getters and setters as necessary for access to the data
- contains the necessary methods to use the data

A class that performs the controller function
- is aware of the model and view
- contains the ActionListener that acts when the view's button is pushed
- gets the user's input from the view, passes it to the model, returns the result back to the view

A class that contains the main() method
- the main() method instantiates the model and view, passing them to an instantiation of the controller

I don't recommend it, but you CAN combine the model and controller into one class that also has the main() method.

It's a simple program, but there's lots to do, about the same no matter how you arrange the parts.

BTW - I don't recommend you use the NetBeans GUI Builder. The GUI builder may initially simplify GUI creation, but the simplification is temporary because it creates code that can't be read or understood by the common man. In other words, the GUI builder doesn't create reusable code that can be easily modified or tailored to fit a slightly different application. Swing is easy enough to learn and do well.
Manny Ruiz
Ranch Hand

Joined: Dec 01, 2010
Posts: 40
I was able to complete the program using netbeans, but i realized it wouldn't be what the project calls for. I will need to find some other GUI tutorials since the ones i got from here used netbeans. So i need to create a class for the GUI, is that correct?
Manny Ruiz
Ranch Hand

Joined: Dec 01, 2010
Posts: 40
Ok I am starting to get really confused here. I have been reading the materials and looking on the web , but I still have no idea what is going on with GUI. I guess I'll start by asking some simple questions which is , when creating a project with a GUI, do you have to create the GUI in a separate class? and if this is the case, does that class only hold info on the GUI? I have noticed that some programs use
"import java.awt.*" and "import javax.swing.*" i assume that means you are importing all aspects of those, but is it necessary? i think i was t
gettimg ahead of myself before
Greg Brannon
Bartender

Joined: Oct 24, 2010
Posts: 563
No, you don't have to create a separate class for the GUI. Sorry to contribute to your confusion. Now that I know where you're starting from, I'll start over.

Here's an example of a simple way to get input from the user in a GUI:



There is a start for your program, but there's work to do:

numberOne is a String that will need to be converted to a number before math can be done,
You need a second number,
Then add the first number to the second and display the answer to the user.
You can use a similar JOptionPane construction for each additional step.

If you get stuck, read the JOptionPane API.

As for your import question, you should read up on that, too.

Manny Ruiz
Ranch Hand

Joined: Dec 01, 2010
Posts: 40
Thank you so much, you are awesome. I feel like I am almost there, but i am having trouble getting it to display the message for the answer.



Do i need to convert the answer to a double as well? why is it asking me to create a variable for "add" if it is already created?

Greg Brannon
Bartender

Joined: Oct 24, 2010
Posts: 563
One would expect you to know that in Java, variables have to be declared before they can be used. You use the variable 'add' in line 9 before it has been declared. How's the compiler supposed to know what kind of variable it is, what value it has?

Reconsider the order of your statements or parts of your statements and rearrange them so that they happen in the proper order. You're almost there.
Manny Ruiz
Ranch Hand

Joined: Dec 01, 2010
Posts: 40
Oops I kinda missed that one. But I have another question about creating a GUI. I need to create a GUI that has a text field, and text label on the first line, the same on the second line and third line. There also has to be a text field for the answer and 3 buttons. so it looks like there are 5 rows of info. Would the best layout to use for this be grid?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39784
    
  28
At this point, I think this thread would sit better in our GIUs forum. Moving.
Thakur Sachin Singh
Ranch Hand

Joined: Jun 15, 2010
Posts: 232

hai see the j2se6 documentation for the JFC/Swing classes & methods....this is best for you.


SCJP 6- 91%, IBM DB2, IBM RAD Certified
Thakur Sachin Singh
Ranch Hand

Joined: Jun 15, 2010
Posts: 232

and you also use some other IDE...like JDeveloper, Eclipse and JBuilder.
Manny Ruiz
Ranch Hand

Joined: Dec 01, 2010
Posts: 40
Currently i am using eclipse, but I still very new not only to Java, but to programming in general. This GUI stuff is really starting to confuse me. Let me see if I at least understand the basics of a GUI. OK so a the first thing to create when doing a GUI is a Jframe. after that JPanels are created to hold the components. Those components are arranged according to the layout. Does this sound right so far?
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10519
    
    9

Manny Ruiz wrote:Currently i am using eclipse, but I still very new not only to Java, but to programming in general. This GUI stuff is really starting to confuse me. Let me see if I at least understand the basics of a GUI. OK so a the first thing to create when doing a GUI is a Jframe. after that JPanels are created to hold the components. Those components are arranged according to the layout. Does this sound right so far?


Absolutely.
A container (e.g. JPanel) will hold other components, which can be containers themselves. i.e. A JPanel can have multiple JPanels inside it. Or it can hold JComponents (e.g. JLabel, JTree etc)
How the child components are laid out is defined by the layout for the parent.
Usually one would have nested panels with different layouts to achieve the desired UI design.


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Manny Ruiz
Ranch Hand

Joined: Dec 01, 2010
Posts: 40
ok then when you want to add components to a GUI, do you have to define them as variables before hand? for example:



This is an example i found on a tutorial. and i have some questions about it. The first line "public class extends JFrame" now does this go within the class, in other words if I created the program 'mortcal' would it look like this?



is it possible to create the GUI in the main method? whats the best way to create GUI's?
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10519
    
    9

ok then when you want to add components to a GUI, do you have to define them as variables before hand? for example:

Only if you want to access them later on.

The first line "public class extends JFrame" now does this go within the class...

One should extend only if you are adding/changing behavior. That being said, I personally always have a class like MyFrame extends JFrame. It depends on you.


is it possible to create the GUI in the main method? whats the best way to create GUI's?

Yes you can.
Just remember to do it like this:

Manny Ruiz
Ranch Hand

Joined: Dec 01, 2010
Posts: 40
Thanks for all the help so far. I am pretty excited to show what I have done.



Its a start for my assignment. Now in regards to the text fields, do i have to add an action listener to those or will what ever amount is put in them be saved in the label, at which point i have to change them to double with parse?
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10519
    
    9


Its always a good idea to follow coding conventions. >> GuiTest


Layouts are the way to go, instead of null layout and bounds.


It is always a good idea to center the frame on the screen. Can't be bothered with screen size and/or resolution? No problem. Just use

do i have to add an action listener to those or will what ever amount is put in them be saved in the label....

In your code, the labels Loan Amount, Interest Rate indicate what the text field represents. Are you referring to those labels?
Manny Ruiz
Ranch Hand

Joined: Dec 01, 2010
Posts: 40
Yes I have to be able to take the amounts entered by the user and calculate a mortgage payment. I know this involves converting text to a double which I understand I was just wondering if the text fields are automatically set up to accept and save text data. What kind of layout should I use to get the same GUI look? How come its better to use layouts.
Manny Ruiz
Ranch Hand

Joined: Dec 01, 2010
Posts: 40
I will look into changing the layout at another time. I think I will be fine as long as the program does what it has to. So i am trying to move onto the calculations. To better understand, i created a simple adding GUI. I am not sure if I approached it the right way, but the double parse is where i am getting an error from eclipse which is "The method parseDouble(String) in the type Double is not applicable for the arguments (JTextField)"
I need some help getting in the right direction. i have already looked through event websites, but it confuses me. Thanks for any help.


Greg Brannon
Bartender

Joined: Oct 24, 2010
Posts: 563
In future, indicate the area of code by line number, method, etc., causing the error message(s). Include the exact error message (copied and pasted), if possible.

Your lines 46 and 47 try to convert a JTextField object to a number. Though the JTextField objects are called 'number1' and 'number2,' they are containers for the user's input, not the actual input. Read the API for the JTextField methods that are available to get the contents of the objects number1 and number2, and substitute the appropriate JTextField.method() for what you have now in lines 46 and 47.

Edit: The JTextField.method() substitution may not work by itself - okay, it WON'T work by itself - because the method() does not return a number directly. You need to be aware of the type of data the method() returns (as specified by the API) and then convert that data to a number before treating it like a number.
Manny Ruiz
Ranch Hand

Joined: Dec 01, 2010
Posts: 40
I am pretty sure I fixed the text fields, dont get any errors, and the code compiles, but now nothing will display. When i run my program, I just get a command line that says "press any key to continue". I feel like I almost have this but there is something wrong here that I dont see.

Greg Brannon
Bartender

Joined: Oct 24, 2010
Posts: 563
At a quick glance: Your addition() method is never called. It controls the display of your GUI.

I should add, this debugging thing is something you need to learn to think through yourself, but it comes with understanding and confidence. In this case, you should observe, "My GUI isn't displaying," then ask, "What makes it display?" Then find the command that's supposed to make the GUI visible, and find out why it's not working.

I think you said you're using Eclipse. Once you find the command that is supposed to make your GUI visible, you might notice that the method() in which that command resides has a yellow squiggly line under it. That's Eclipse telling you that that method() is never used. Ta da! Without the yellow line, your next step would be to figure out why the command in the method isn't working, tracing it backwards, and you'd eventually realize that the method() is never called.
Manny Ruiz
Ranch Hand

Joined: Dec 01, 2010
Posts: 40
I though i was calling it with the following:



doesnt this tell the listener to perform the addition method when the add button is clicked?
Greg Brannon
Bartender

Joined: Oct 24, 2010
Posts: 563
But that call is IN the method addition(). main() runs and calls addex(), addex() runs and then . . . the program ends.

Lines 59 - 61 and 65 - 57, critical to the operation of your GUI, are never executed. Where might you put those lines? (Read my first line again.)
Manny Ruiz
Ranch Hand

Joined: Dec 01, 2010
Posts: 40
in the main method?
Greg Brannon
Bartender

Joined: Oct 24, 2010
Posts: 563
You had a 50% chance . . . and there's more than one right answer. There is, however, a best answer based on what's easiest and most appropriate for this simple program.

Where - in what part of the program - did you add listeners to other GUI components?

You're doing good, by the way. You've come a long ways.
Manny Ruiz
Ranch Hand

Joined: Dec 01, 2010
Posts: 40
thanks i feel like i almost have it but there is something wrong that im sure is staring me right in the face, but for some reason i cannot see it. here is where i moved the event handler-is this the right place?

Greg Brannon
Bartender

Joined: Oct 24, 2010
Posts: 563
You're on the right track. Put the code to add a listener to your add button as you showed, and move your exit button listener up to the corresponding place in addex.

Then, you have to ask why the GUI is controlled in the addition() method. Does it work? If not, maybe the statements in lines 71 - 75 need to be moved up to be the last lines of addex.

I made those 3 changes locally, and I can see your GUI. There's more work to do, but at least with those changes you'll be able to SEE what's going on.
Manny Ruiz
Ranch Hand

Joined: Dec 01, 2010
Posts: 40


Ok i made the changes, and thank the maker I can see the GUI, now the only problem is the program doesnt work.

when i click the add button i get the following error:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at addex.addition(addex.java:67)
at addex.access$0(addex.java:65)
at addex$1.actionPerformed(addex.java:46)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Greg Brannon
Bartender

Joined: Oct 24, 2010
Posts: 563
Looks like the world's coming to an end, doesn't it. But it's not that bad.

How I read these:
Start at the top with "Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String"
I pick out the only thing I can understand, "empty String"
Then I keep reading down the list, looking for a line number from my program, noting other words I can understand along the way:
"Unknown Source"
"Unknown Source"
then addex.java:67

That means there's something going on at line 67. "Empty String" and "Unknown Source" could be (and probably are) related.

So what's going on in line 67? You're trying to parseDouble(x). Oh yeah, parseDouble was mentioned in the third error line, too.

Conclusion: there must be something wrong with the 'x' part of line 67. Possiblities are that parseDouble doesn't know what 'x' is, can't see it, it's not a legal input, something.

Whaddya think? You might look up parseDouble (you probably did already) to see what argument it expects. Look closely at 'x' to figure out why that might be a problem. Think about visibility and scope as you stare at 'x' and 'y' in lines 67 and 68.
Manny Ruiz
Ranch Hand

Joined: Dec 01, 2010
Posts: 40
Do i need to move the addition method up in the code to above where the method is called? BTW i changed the x, y to a & b since i noticed it used x & y in the GUI dimensions.
Manny Ruiz
Ranch Hand

Joined: Dec 01, 2010
Posts: 40
ok the answer to my question as far as i can tell is no. i moved the addition method to a few different places and kept getting the same error, the only thing that changed was the line number where the error is. Im looking at the addition method and i cant tell whats the problem, the double numbers are defined and parsed as far as i can tell.
Greg Brannon
Bartender

Joined: Oct 24, 2010
Posts: 563
When you assign the values of x and y at lines 34 and 39, respectively, will there be any user entry in those text fields? Probably not, since the error is saying there's a problem with x and y. When will there be user-entered data in the text fields from which the data for x and y comes? I hope there will be valid data in those fields when the user presses the Add button. So maybe, assigning x and y shouldn't happen until the Add button is pressed. Where in your program do you know the Add button has been pressed?

BTW - even the user pressing the Add button won't be a guarantee that there's valid data in those text fields, but that's something to think about later. For now, assume there will be valid data for your program to use.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: First GUI program