17 - Create a Sample Calculator

Share:
Create a Sample Calculator

In this section, you'll be writing a calculator programme that makes use of forms. The form will have buttons and a text box. We'll start off with a very simple calculator that can only add up, and then extend its capabilities so that it can subtract, divide and multiply. The calculator will look something like this:


NetBeans and Java Forms

Developing a Graphic User Interface (GUI) using Java can be an art-form in itself, as there's quite a lot to get used to: Components, Containers, Layout Managers, and a whole lot more besides. The NetBeans development environment, however, has greatly simplified the creation of forms, and we'll use this to drag and drop controls onto a frame.
Rather than go through reams of GUI theory, we'll just jump straight into it.
Create a new project for this by clicking File > New Project from the NetBeans menu at the top. Select Java > Java Application from the list boxes, and then click the Next button.
On step 2 of the wizard, type MyCalculator as the project name. At the bottom, uncheck "Create main class". This is because a main method will be created for us by NetBeans when we add a form. Step 2 of the wizard should look like this:

Now Click the Finish button, and NetBeans will create the project, but not much else. Have a look at the Projects area on the left in NetBeans and you should see this (If you can't see the Projects area, click Window > Projects from the NetBeans menu at the top).


Now we at the Java Form. When we create java form it will be created its own class file.

Right click the project name in the project window and add JFrame Form like this.



Select New > JFrame Form from the menu. When you do, you should see the following wizard appear:


Here, you are being asked for a name for your Class, and a package name. We've already created the project, and called it MyCalculator. The package name and class will go into the project. So, for your Class Name type GUICalculator. In the blank package text box, type Calculator. So we're creating a class called GUICalculator, which is in the Calculator package, which is in the MyCalculator project.

Click the Finish button to complete the process.

No comments