Lesson 3 - Simple calculator in Java Swing
In the previous lesson, Java Swing under the hood, we explained how Swing works and learned to center the application window. In today's lesson, we're going to have a look at events and create a simple calculator. It'll look like this:
Preparing the form
Create a new project (Java Application without the main class) named
Calculator
. Add a new JFrame
Form called
CalculatorJFrame
to the project. In Properties, set the title to
Calculator
. When creating applications, we usually start with the
form design. Let's drag several components onto the form from the palette. We'll
need:
- 2x Label
- 1x Button
- 2x Spinner
- 1x ComboBox
Label
We already know label; it's simply an explanatory text.
If we don't use components from the code, we don't have to name them. If so, we should rename them (see below) and then we access the component by this name from the code.
We already know the text
property. It contains what is displayed
in the label. We'll only use one of the labels to display the text "=". So, set
it up. We'll use the second label to display the result. Since we'll set its
value by the program, we'll rename it to resultJLabel
(with the
capital letter J
). To do this, right-click the label and choose
Change Variable Name...:
We'll set the text to "0". And we can increase the font of the result label
to 16
.
Button
A button is simply a component that calls a method when clicked (more
precisely triggers an event). In our case, the button will be named
calculateJButton
and its text will be Calculate
. We'll
assign the event to the button later.
Spinner
Spinner is the first component to enter a value that we'll mention. We can enter a whole number in it (and also a decimal number if we enable it). The advantage of entering numbers with this component is that the user can't enter an invalid value. If we parsed the number from a Text Field (we'll show these in the following lessons), our application might crash due to invalid input. It's always easier to choose the right component than to validate the user input.
We'll name the components as number1JSpinner
and
number2JSpinner
. Note that the name should always contain the
component type as well. Like that, it's possible to have, for example, both
ageJLabel
and ageJSpinner
, where the label is the
description of the field serving to enter an age and the spinner is then that
field. Moreover, our code is then much clearer. Names such as
numberSpn
, calculateBtn
and so on are sometimes used
as well.
ComboBox
We're almost finished. Combo Box is a drop-down list with several predefined elements. The elements can either be added in the designer or from the code, even at runtime. This applies to all components, we can set all properties found in the designer from the code as well.
Let's name the component operationJComboBox
and click on the
"..." button next to the Model property. In the newly opened window, we'll list
the options to choose from in the Combo Box. We write each option on a separate
line, in our case, it'll be +
, -
, *
,
/
:
Note: The items may not only be strings but also objects. We'll show it later.
We can set the default selected item with the selectedIndex
property, 0
is the first value.
We'll arrange the components on the form as shown at the beginning of the article.
Event handling
So we just have to respond to the button click event. Click the button twice, and a new method will be generated in our code:
private void calculateJButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: }
When we expand the generated initComponents()
method, we find
the button with a few lines setting its ActionListener
. This is an
object that can respond to an action (a click on the button in our case) and
calls the above method.
calculateJButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { calculateJButtonActionPerformed(evt); } });
If you've finished reading our course on object-oriented programming, you should know this is an anonymous class. If not, it doesn't matter at all. The key is that you have an idea of how the connection between the component and the click-handling method is created.
Let's go back to the designer (the Design button in the top bar) and select the button. In the Properties window, you can switch between Properties and Events (the Properties and Events buttons).
Here we can see our actionPerformed
event (this is the click
event). We could remove it from here and possibly add it again. Some components
have special events for which we generate methods from here.
Never remove events by deleting the handler method from the code, the designer would stop working, and you would have to correct the file (specifically, remove the line with the registration of a non-existent method to the event). While NetBeans will not allow you to do this, it's possible to delete it e.g. in another editor. The only right way is through the designer.
Calculation
Let's proceed to the calculation itself. The code won't be complicated. In
the handler method, we'll simply use if
statements for the selected
item of the operationComboBox
and calculate the result accordingly.
Then we'll set the result as the text of resultJLabel
. We shouldn't
forget to handle the division by zero.
The code of the event handler method might look like this:
private void calculateJButtonActionPerformed(java.awt.event.ActionEvent evt) { // declaration of variables String operation = String.valueOf(operationJComboBox.getSelectedItem()); int number1 = (int)number1JSpinner.getValue(); int number2 = (int)number2JSpinner.getValue(); double result = 0; // calculation if (operation.equals("+")) result = number1 + number2; else if (operation.equals("-")) result = number1 - number2; else if (operation.equals("*")) result = number1 * number2; else if (operation.equals("/")) { if (number2 != 0) result = number1 / number2; else { result = 0; JOptionPane.showMessageDialog(null, "Cannot Divide by Zero!"); } } resultJLabel.setText(String.valueOf(result)); }
First, we store the values from the components to variables, so it's
more readable. We get the selected Combo Box item using the
getSelectedItem()
property, which is of the Object
type. In our case, we have to convert it to String
. We could also
work just with the numeric index of the item using
getSelectedIndex()
. Since Spinner
returns the value as
an Object
type, we must cast it to int
.
In case of the zero divider, we display a MessageBox using the static
JOptionPane
class. It contains the showMessageDialog()
method. Finally, we pass the result to resultJLabel
. Unlike the
console, where numbers could be simply printed out, here we must first convert
the number to String
.
If we turn off the resizable property in the Properties window, it won't be possible to resize the window, which is useful for our application.
This app may already be worth sending to someone. By pressing the icon with
the broom and the hammer (Clean and Build Project) in Netbeans, we'll generate a
dist/
folder in the project folder where you can find the
Calculator.jar
file. This is an executable file for your
application. Of course, you must have Java installed to run it. But most people
have it.
The project source code is attached to the article as always. The next time, Birthday Reminder in Java Swing - Form design, we'll create a more complex application with multiple forms. It'll be a birthday reminder.
Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.
Download
By downloading the following file, you agree to the license terms
Downloaded 82x (28.27 kB)
Application includes source codes in language Java