1. Technology

Creating A Simple Calculator to Handle Button Events


1 of 7

A Simple Calculator

One of the most common events to occur in any graphical user interface is when a user clicks on a button. When his happens it's up to the Java application to perform some action based on the button being clicked. The good news is Java developers don't have to worry about the mechanics behind waiting for an event to happen - the operating system and the Java platform combine to monitor and pass on the message that an event has occurred. The Java application can then get this message by using event listeners. For a JButton the event listener is called the ActionListener.

Before we get too deeply into discussing ActionListeners lets build a user interface for a simple calculator. It will have a JTextField at the top to show what numbers are being pressed and 12 JButtons - one for each number 1 to 9 and the other three to handle adding, subtracting and the equals button.

Note: I'm not going to explain the creation of the graphical interface but show the program here without any ActionListeners added. To find out more about building this user interface have a look at Coding a Simple Graphical User Interface - Part I, An Overview of Layout Managers, Using the Border Layout, and Working with the GridLayout. The full program listing for this Java program can be found in A Simple Calculator Example Program.

  1. About.com
  2. Technology
  3. Java
  4. Create User Interfaces
  5. Handling Events
  6. Creating A Simple Calculator to Handle Button Events

©2014 About.com. All rights reserved.