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

If you try to compile this class, you'll get an error message saying that the class must implement the method actionPerformed(ActionEvent e). That's right, you're breaking the contract that forces you to implement all methods that might have been declared in the interface. Let's fix this error:


import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class CalculatorEngine implements ActionListener {

public void actionPerformed(ActionEvent e){
// An empty method is also allowed here, even though nothing
// is going to happen when the JVM calls it
}
}
The next version of this class will display a message box from the method actionPerformed(). You can display any messages using the class JOptionPane and its method showConfirmDialog(). For example, the class CalculatorEngine (see below) displays the following message box:

There are different versions of the method showConfirmDialog(), and we are going to use its four-arguments version. In the code below, null means that this message box does not have the parent window, the second argument contains the title of the message box, then goes the message itself, and the fourth argument allows you to select a button(s) to be included in the box (PLAIN_MESSAGE means that only a single button OK will be displayed in the message box).


import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
public class CalculatorEngine implements ActionListener {

public void actionPerformed(ActionEvent e){
JOptionPane.showConfirmDialog(null,
"Something happened...", "Just a test",
JOptionPane.PLAIN_MESSAGE);
}
}
In the next section I'll explain you how to compile and run the next version of our calculator that will display the Something Happened message box.

Registering Components with ActionListeneter

Who and when will call our code in the method actionPerformed()? The JVM itself will call this method if you register the calculator's buttons with the class CalculatorEngine! Just add the following two lines at the end of the constructor of the class Calculator.java to register the button zero with our action listener:


CalculatorEngine calcEngine = new CalculatorEngine();
button0.addActionListener(calcEngine);
From now on, every time when the user clicks on the button0, JVM calls the method actionPerformed() on the object CalculatorEngine. Compile and run the class Calculator now, and click on the button zero - it'll display the Something happened message box! Other buttons remain silent because they are not registered yet with our action listener. Keep adding similar lines to bring all buttons to life:

button1.addActionListener(calcEngine);
button2.addActionListener(calcEngine);
button3.addActionListener(calcEngine);
button4.addActionListener(calcEngine);
...
What's the Source of an Event?

The next step is to make our listener a little smarter - now it'll display different message boxes, depending on which button was pressed. When an action event occurs, JVM calls the method actionPerformed(ActionEvent) on your listener class, and it provides a valuable information about this event in the argument ActionEvent. You can get this information by calling appropriate methods on this object.

Casting

In the next example we are finding out which button has been pressed by calling the method getSource() of the class ActionEvent - the variable e is a reference to this object that lives somewhere in memory. But according to Java documentation, this method returns the source of the event as an instance of the type Object, which is a superclass of all Java classes including window components. That's why this method that works for all components, which are subclasses of Object. Since we know for sure, that in our window only buttons can possibly be the reasons of the action event, we cast the returned Object to the shape of a JButton by placing (JButton) in parentheses in front of the method call:


JButton clickedButton = (JButton) evt.getSource();
When you declare a variable for storing a reference to the instance of an object of particular class, this variable has to have either the data type of this class or of one of its superclasses.

If the class JButton is a subclass of the class Object (it does not have to be a direct subclass), each of these lines is correct:


JButton clickedButton = new JButton();
Object clickedButton = new JButton();
The variable clickedButton was declared with the type JButton, and even though the method getSource() returns the data of type Object, we say to JVM, "Don't worry, I know for sure that I'm getting an instance of a JButton".

Only after performing casting from the type Object to the type JButton we are allowed to call the method getSource() that belongs to a class JButton.


import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.JButton;
public class CalculatorEngine implements ActionListener {
public void actionPerformed(ActionEvent e){
// Get the source of this action
JButton clickedButton=(JButton) e.getSource();
// Get the button's label
String clickedButtonLabel = clickedButton.getText();

// Concatenate the button's label
// to the text of the message box
JOptionPane.showConfirmDialog(null,
"You pressed " + clickedButtonLabel,
"Just a test",
JOptionPane.PLAIN_MESSAGE);
}
}

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.