Home Tutorials Java Creating a Calculator GUI in Java

Popular

Share |
Creating a Calculator GUI in Java PDF Print E-mail
Written by Joe Stead   
Tuesday, 16 March 2010 23:48

So you understand how basic Java operates so far, you understand what variables are and how to layout your code. In one of my previous tutorials, I demonstrated how you could use basic input to make a simple calculator which adds two values together specified by the user. However that program wasn't really user-friendly. It had to Input Dialogs appear and one MessageDialog requesting/displaying the appropriate information. Which is all well and good, but not very user friendly.

The calculator on Windows machines looks something like this: Windows Calulator Which is a lot nicer and easier to use. So we are going to make something similar to this in Java.

First of all we need to make a new class, lets call it caclInterface. As you can see, on the windows calculator we have 1 text field and a few buttons. On our calculator we will have 17 buttons. 0-9 / * + - = Clear and Backspace, I know it isn't as many as the windows calculator, but this is going to be enough to get us started with.

We will also need something called a JFrame, a JFrame is part of the swing library in Java, as is the JButton, and the JTextField, the JOptionPane is also part of the swing library (as well as a lot of other stuff, for a full list view the API).

So now we know exactly what we will need to make our calculator GUI, we can begin. First we need to import the classes we will require, and make a constructor:

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;

public class calcInterface {


	
	public calcInterface(){
		
		
		
		
	}

}

The JFrame I have imported is basically a window on the screen, a JFrame is a container, it holds our components like the JButton and the JTextField.

 

We need to do something with our container before it will show anything on screen. We need to add the following piece of code inside our class, personally I prefer just outside of the constructor.

JFrame wind = new JFrame("My first calculator");

This piece of code may look similar, in my previous tutorials when I write a main method I use something similar to this, I use

ClassName myClassName = new ClassName();

 

The JFrame is exactly the same, only it has a parameter which I have entered as My First Calculator. This is the title of the window, the Title of my window at the moment is "Swivvet Article Writer - Swivvet Dev." (Yes, I made a program to make article writing easier, no I won't release any more information on it.)

So now we have a JFrame to play with, what about our JTextField and JButtons'. We need to do something similar with them. For now we will leave out the JButton component, this is because we are working with 17 buttons and there is a faster way to combat this problem.

JTextField txtOut = new JTextField(10);

This time I have put 10 as the parameter. A JTextField can take up to three different parameters, a Document (I will explain this in a different tutorial), a String to have a default text value, and the number of columns.

 

Great, so now all we need to do is add the JTextField named txtOut to our JFrame, set the JFrame to visible and we will see it on screen! This can be achieved by adding the following into your constructor

wind.add(txtOut);
		
		wind.setVisible(true);

And adding a main method

public static void main(String[] arg0)
{
		calcInterface myCalcInterface = new calcInterface();
	}

Ok, well we do get an output, but it is a mess, the JTextField takes up the whole size of the screen, the JFrame starts tiny so we can't see anything and its just a mess. We need to have some kind of LayoutManager in the program so we can organise our components a lot easier.

 

By Default the JFrame has a default LayoutManager of something called a BorderLayout. Which is fine, the BorderLayout is great, but it does stretch the centre component to take up any empty space, which is not what we want. We will use something called JPanels (another container) to hold our components and manage our layouts. So let's go back to the top of our program where we imported the JFrame, JTextField and JButton classes and add a new line to it.

import javax.swing.JPanel;

Now we have access to the JPanel, we need to work out how many we are going to need. As I mentioned before, by default a JFrame has a BorderLayout, this basically means it has a border around it, here is an example, Border Layout Example.

 

So we have 5 sections, the ones we are interested in will be the North section (our JTextField will sit nicely here, along with our clear and backspace buttons), the center (our numbers can sit here) and the East (where we can have our buttons to perform the calculation). So that is three sides, so we will need 3 JPanels...

JPanel pnlNorth, pnlEast, pnlCenter;

We will then need to instantiate them, so we need to add this into our constructor, I added it to the top (just to keep things tidy).

pnlNorth = new JPanel();
		pnlEast = new JPanel();
		pnlCenter = new JPanel();

 

So we have our JPanels now, but each one of these may require a layout for themselves. By default JPanels use FlowLayout this is basically starting in the middle and flowing out (like centred text on Word). FlowLayout can also be aligned Left/Right. For pnlNorth we want our JTextField (txtOut) to be aligned left so we have space for the clear and backspace buttons. We can do this quite simply...

pnlNorth = new JPanel(new FlowLayout(FlowLayout.LEFT));

Great, now we have a JPanel which will set everything on the left side of our JFrame, but the JPanel won't be visible, we haven't added it to the JFrame, this is quite simple to do, and is similar to how we added the JTextField previously

wind.add(pnlNorth, BorderLayout.NORTH);

However, you will notice one or two problems with the above code listings, FlowLayout and BorderLayout have not been imported in, we need to add two new imports to get them to work properly without the compiler chucking errors at us.

import java.awt.BorderLayout;
import java.awt.FlowLayout;

Now we will have a JPanel in the North edge of the JFrame, all we need to do now is add in the JTextField we made earlier

pnlNorth.add(txtOut);

Now our North Panel is complete up to this stage.

 

What about the center panel? That can't use a FlowLayout, we'd have a long line of buttons instead of a grid of them. Luckily for us Java has a GridLayout, Large grids can get quite confusing and should be avoided if possible, unfortunately in a Grid Layout, every single Grid has to have something in, and you can't specify where your components go, they go in left to right, top to bottom, until you've either filled in every grid or ran out of components. First of all we need to import our GridLayout

import java.awt.GridLayout;

and then we need to change our pnlCenter to have this layout, now, a GridLayout has a few parameters(some are optional).. The GridLayout parameters, in order, are as follows

new GridLayout(rows,cols,hgap,vgap);

All of which are int variables. In our center panel, we need to have 10 buttons, so we will go for 3 columns, and 4 rows (which leaves 2 spare grids). Our pnlCenter code then changes to this:

pnlCenter = new JPanel(new GridLayout(4,3));

 

So now we have our Center panel sorted, we will move onto the East Panel. We will require 5 JButtons going vertically down the East Panel, now there are a few different ways we could do this, but to keep things simple let's use another GridLayout, we need 1 column, and 5 rows. (5 buttons = "+" "-" "=" "*" "/"). This is fairly simple and pretty much the same as the Center only changing the two parameters we enter.

pnlEast = new JPanel(new GridLayout(5,1,0,5));

Notice this time I have used the two additional parameters, I have set the hgap (Horizontal Gap) to 0, this won't do anything as our Grid is going to be 1 column wide and vertical, so 0 suits it best, I have set a Vertical Gap of 5, so we will have a bit of spacing between each button.

 

As I mentioned earlier, 17 buttons to add individually is a lot, and it is, however for the buttons on the East side, we will need to do it manually, we will also need to do it manually for the two buttons on the top. Now our JButton comes into use for the first time. Above your constructor you should have something which is similar to this:

JFrame wind = new JFrame("My First Calculator");
	JTextField txtOut = new JTextField(10);
	JPanel pnlNorth, pnlEast, pnlCenter;

Below this, you need to add in a new line which will look like this:

JButton btnAdd, btnMinus, btnDivide, btnMulti, btnEqual, btnBack, btnClear;

Now we have 7 buttons, we need to instantiate them, just like we did for the JTextField, only the parameters will be different once again. We will need to enter just one parameter, and that will be a String of the text we wish to appear on the button. So inside the constructor we need to add this:

btnAdd = new JButton("+");
		btnMinus = new JButton("-");
		btnDivide = new JButton("/");
		btnMulti = new JButton("*");
		btnEqual = new JButton("=");
		btnBack = new JButton("Backspace");
		btnClear = new JButton("Clear");

Now we need to add our buttons to our JPanel, but before we do this, we need to add our pnlCenter and pnlEast to our JFrame. Find where you added pnlNorth and add the following below it:

wind.add(pnlCenter, BorderLayout.CENTER);
		wind.add(pnlEast, BorderLayout.East);

We can now add our JButtons to pnlEast....

pnlEast.add(btnAdd);
		pnlEast.add(btnMinus);
		pnlEast.add(btnDivide);
		pnlEast.add(btnMulti);
		pnlEast.add(btnEqual);

And obviously we need to update the North JPanel to have the Clear and Backspace buttons..

pnlNorth.add(btnClear);
		pnlNorth.add(btnBack);

We now have an almost complete calculator GUI. There is one thing we are missing though, the number buttons!

Now, I've been putting this section of for quite a while, as it introduces something completely new, a Loop. Loops are something which will continue to do something until a certain clause is met. For our calculator we will be using a [b]for[/b] loop, the basic structure is like this:

for(int i = 0; i <10; i++){

System.out.println(i);

}

This outputs 0 1 2 3 4 5 6 7 8 9 into the Java console.

 

The first part, "int i = 0;" is just declaring a variable named "i". The second part simply tells the loop to continue until i is no longer less than ten. The third part tells the loop to increment i by one every time. This is done by using the "++". If we wished to decrement by one, we could have used "--". I will cover more on this in a different tutorial.

Hmm, the output of that above loop looks extremely similar... we need the numbers 0 - 9 to appear in our JButtons in our Center Panel. So now what we can do, is change what the loop does. In our constructor we have added every component we have required so far, so all that is left is our numbers, this is easily done now we have our loop, all we need to do is change its behaviour....

for (int i=0; i <10; i++) 
		{
		 JButton btnNum = new JButton(""+i);
		 pnlCenter.add(btnNum);
		}

As you can see, the above piece of code is nothing new to us, the only thing we have done differently is the way we add the String for the JButton, we have done it like that because i is an int variable, so trying to add an int directly into it would give us an error, so we make a blank String first and then add i to the String.

 

Now our calculator GUI is nearly complete. All we need to do is add a size of the JFrame so it doesn't always appear small. Now, we could add the following code to the bottom of our constructor just above where we set it visible:

wind.setSize(400,300);

Which would set the JFrame size, or we could let Java get the best possible size for us so all the components are packed in nicely...

wind.pack();

Now, everything should be great, but you may notice when you close your program, you will notice that your program doesn't actually continue running, it just doesn't display the JFrame any more, this is fixed quite easily by adding the following into your code:

wind.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

That's it! Your calculator interface should look something like this: Java Calculator

 

Post any questions on the forums!

 
Share |

Login

Sponsors