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

We'll program all these actions in the class CalculatorEngine. While reading the code below, remember that the method actionPerformed() will be called after each button click and the data between these method calls will be stored in the variables selectedAction and currentResult. Here's the class CalculatorEngine:


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

public class CalculatorEngine implements ActionListener {

Calculator parent; //a reference to Calculator window
char selectedAction = ' '; // +, -, /, or *

double currentResult =0;

// 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();
String dispFieldText=parent.displayField.getText();

double displayValue=0;

//Get the number from the text field
// if it's not empty
if (!"".equals(dispFieldText)){
displayValue= Double.parseDouble(dispFieldText);
}
Object src = e.getSource();

// For each action button memorize selected
// action +, -, /, or *, store the current value
// in the currentResult, and clean up the display
// field for entering the next number

if (src == parent.buttonPlus){
selectedAction = '+';
currentResult=displayValue;
parent.displayField.setText("");
} else if (src == parent.buttonMinus){
selectedAction = '-';
currentResult=displayValue;
parent.displayField.setText("");
}else if (src == parent.buttonDivide){
selectedAction = '/';
currentResult=displayValue;
parent.displayField.setText("");
} else if (src == parent.buttonMultiply){
selectedAction = '*';
currentResult=displayValue;
parent.displayField.setText("");
} else if (src == parent.buttonEqual){
// Perform the calculations based on selectedAction
// update the value of the variable currentResult
// and display the result
if (selectedAction=='+'){
currentResult+=displayValue;
// Convert the result to String by concatenating
// to an empty string and display it
parent.displayField.setText(""+currentResult);
}else if (selectedAction=='-'){
currentResult -=displayValue;
parent.displayField.setText(""+currentResult);
}else if (selectedAction=='/'){
currentResult /=displayValue;
parent.displayField.setText(""+currentResult);
}else if (selectedAction=='*'){
currentResult*=displayValue;
parent.displayField.setText(""+currentResult);
}
} else{
// For all numeric buttons append the button's
// label to the text field
String clickedButtonLabel= clickedButton.getText();
parent.displayField.setText(dispFieldText + clickedButtonLabel);
}
}
}
The comments in the code above will help you understand how this class works.

The final version of the calculator window will look like this:


The class Calculator performs the following steps:

  1. Create and displays all window components.
  2. Create an instance the event listener CalculatorEngine.
  3. Pass to the engine a reference to the itself .
  4. Registers with this listener all components that can generate events.
Here's the final version of the class Calculator:

import javax.swing.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;

public class Calculator {
// Declare and instantiate window components
JButton button0=new JButton("0");
JButton button1=new JButton("1");
JButton button2=new JButton("2");
JButton button3=new JButton("3");
JButton button4=new JButton("4");
JButton button5=new JButton("5");
JButton button6=new JButton("6");
JButton button7=new JButton("7");
JButton button8=new JButton("8");
JButton button9=new JButton("9");
JButton buttonPoint = new JButton(".");
JButton buttonEqual=new JButton("=");
JButton buttonPlus=new JButton("+");
JButton buttonMinus=new JButton("-");
JButton buttonDivide=new JButton("/");
JButton buttonMultiply=new JButton("*");
JPanel windowContent = new JPanel();
JTextField displayField = new JTextField(30);

// Constructor
Calculator(){
// Set the layout manager for this panel
BorderLayout bl = new BorderLayout();
windowContent.setLayout(bl);

// Add the display field to the top od the window
windowContent.add("North",displayField);

// Create the panel with the GridLayout
// that will contain 12 buttons - 10 numeric ones, and
// buttons with the point and the equal sign

JPanel p1 = new JPanel();
GridLayout gl =new GridLayout(4,3);
p1.setLayout(gl);

p1.add(button1);
p1.add(button2);
p1.add(button3);
p1.add(button4);
p1.add(button5);
p1.add(button6);
p1.add(button7);
p1.add(button8);
p1.add(button9);
p1.add(button0);
p1.add(buttonPoint);
p1.add(buttonEqual);

// Add the panel p1 to the center area of the window
windowContent.add("Center",p1);
// Create the panel with the GridLayout
// that will contain 4 action buttons -
// Plus, Minus, Divide and Multiply
JPanel p2 = new JPanel();
GridLayout gl2 =new GridLayout(4,1);
p2.setLayout(gl2);
p2.add(buttonPlus);
p2.add(buttonMinus);
p2.add(buttonMultiply);
p2.add(buttonDivide);

// Add the panel p2 to the east area of the window
windowContent.add("East",p2);

// Create the frame and add the content pane to it
JFrame frame = new JFrame("Calculator");
frame.setContentPane(windowContent);

// set the size of the window to be big enough to
// accomodate all window controls
frame.pack();

// Display the window
frame.setVisible(true);

// Instantiate the event listener and
// register each button with it
CalculatorEngine calcEngine = new CalculatorEngine(this);

button0.addActionListener(calcEngine);
button1.addActionListener(calcEngine);
button2.addActionListener(calcEngine);
button3.addActionListener(calcEngine);
button4.addActionListener(calcEngine);
button5.addActionListener(calcEngine);
button6.addActionListener(calcEngine);
button7.addActionListener(calcEngine);
button8.addActionListener(calcEngine);
button9.addActionListener(calcEngine);

buttonPoint.addActionListener(calcEngine);
buttonPlus.addActionListener(calcEngine);
buttonMinus.addActionListener(calcEngine);
buttonDivide.addActionListener(calcEngine);
buttonMultiply.addActionListener(calcEngine);
buttonEqual.addActionListener(calcEngine);
}

public static void main(String[] args) {
// Instantiate the class Calculator
Calculator calc = new Calculator();
}
}

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.