CEP Breaking News, Articles, Feature Stories and Blog Posts

CEP on Ulitzer

Subscribe to CEP on Ulitzer: eMailAlertsEmail Alerts newslettersWeekly Newsletters
Get CEP on Ulitzer: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn


cep Authors: Tony Shan, Liz McMillan, Bob Gourley, Charles Rich, AppDynamics Blog

Related Topics: Java Developer Magazine, CEP on Ulitzer

Java Developer : Article

Java Basics: Processing GUI Events

Lesson 13 of Yakov Fain's Popular Online Series

For example, if you press the button five, you'll see the following message box:


But what if window events are produced not only by buttons, but by some other components as well? We do not want to cast every object to JButton! For these cases you should use a special Java operator called instanceof to perform the proper casting. The next example first checks what type of object caused the event, and then performs casting to either JButton or JTextField:


public void actionPerformed(ActionEvent evt){

JTextField myDisplayField=null;
JButton clickedButton=null;

Object eventSource = evt.getSource();

if (eventSource instanceof JButton){
clickedButton = (JButton) eventSource;
}else if (eventSource instanceof JTextField){
myDisplayField = (JTextField)eventSource;
}
}
Our calculator has to execute different portions of the code for each button, and the next code snippet shows how to do this.

public void actionPerformed(ActionEvent e){

Object src = e.getSource();

if (src == buttonPlus){
// Code that adds numbers goes here
} else if (src == buttonMinus){
// Code that subtracts numbers goes here
}else if (src == buttonDivide){
// Code that divides numbers goes here
} else if (src == buttonMultiply){
// Code that multiplies numbers goes here
}
}
How to Pass Data Between Classes

Actually, when you press a numeric button on the real calculator, it does not show a message box, but rather displays the number in the text field on top. Remember that windows components are located in the class Calculator, while the actual calculations will be done in the class CalculatorEngine. Hence a new challenge - we need to be able to reach the attribute displayField of the class Calculator from the method actionPerformed() of the class CalculatorEngine. This can be done if we define in the class CalculatorEngine a variable that will store a reference to the instance of the object Calculator.

We are going to declare a constructor in the next version of the class CalculatorEngine. This constructor will have one argument of type Calculator. Don't be surprised, method arguments can have data types of the classes created by yourself!

JVM executes the constructor of the CalculatorEngine instance during the creation of this object in memory (see lesson 2 on constructors <...>). The class Calculator instantiates the CalculatorEngine object, and passes to the engine's constructor the reference to itself using the keyword this:


CalculatorEngine calcEngine = new CalculatorEngine(this);
This reference contains a location of the calculator's instance in memory. Where exactly? Who cares, this is not C++, you know! The engine's constructor stores this value in the member variable parent, and eventually will use it in the method actionPerformed() to access the calculator's display field.

parent.displayField.getText();
...
parent.displayField.setText(dispFieldText + clickedButtonLabel);
These two lines where taken from the next code sample.

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;

public class CalculatorEngine implements ActionListener {

Calculator parent; // a reference to the Calculator

// Constructor stores the reference to the
// Calculator window in the member variable parent
CalculatorEngine(Calculator parent){
this.parent = parent;
}

public void actionPerformed(ActionEvent e){
// Get the source of this action
JButton clickedButton = (JButton) e.getSource();

// Get the existing text from the Calculator's
// display field
String dispFieldText = parent.displayField.getText();

// Get the button's label
String clickedButtonLabel = clickedButton.getText();

parent.displayField.setText(dispFieldText + clickedButtonLabel);
}
}
Finishing the Calculator

Let's write some simple rules (a functional specification) of how our calculator should work:

1.  The user enters all the digits that represent the first number.

2.  If the user hits one of the action buttons +, -, / or * , then store the first number and selected action in member variables, and erase the number from the display text field.

3.  The user enters the second number and hits the button equals .

4.  Convert the String value from the text field into a numeric type double to be able to store large numbers with a decimal point. Perform selected action using this value and the number stored in the variable from step 2.

5.  Display the result from step 4 in the text field and store this value in the variable that was used in step 2.

More Stories By Yakov Fain

Yakov Fain is a Java Champion and a co-founder of the IT consultancy Farata Systems and the product company SuranceBay. He wrote a thousand blogs (http://yakovfain.com) and several books about software development. Yakov authored and co-authored such books as "Angular 2 Development with TypeScript", "Java 24-Hour Trainer", and "Enterprise Web Development". His Twitter tag is @yfain

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.