Welcome!

Java IoT Authors: Kevin Sparenberg, Liz McMillan, Karyn Jeffery, Yeshim Deniz, Elizabeth White

Related Topics: Java IoT

Java IoT: Article

Java Basics: Processing GUI Events

Lesson 13 of Yakov Fain's Popular Online Series

Various events may happen to a running program: a user clicks on a button in a window, the Web browser decides to re-paint the window, and so on. I'm sure, you've tried to click on the buttons of the calculator from the lesson on Swing Basics, but these buttons were not ready to respond to your actions yet. This time, let's teach window components to react on such actions.

Each window component can listen to and process a number of events, and your program has to register window components with Java classes called listeners. You should make components listen to only those events they are interested in. For example, when a person moves the mouse cursor over the calculator button, it's not important where exactly the mouse pointer at the click-moment as long as it was right above the button. That's why you do not need to register the button with Java's MouseMotionListener. On the other hand, this listener is handy for all kinds of drawing programs.

Calculator's buttons should register themselves with the ActionListener that can process button-click events. All these listeners are special Java structures called interfaces.

Interfaces

Most of the GUI-related classes define methods that perform various actions, for example react to button clicks, react to mouse movements, and so on. A combination of such actions/reactions is called a class behavior.

Interfaces are special Java constructs that just declare a set of particular actions without containing an actual code that implements these actions, for example:


interface MouseMotionListener {
void mouseDragged(MouseEvent e);
void mouseMoved(MouseEvent e);
}
As you can see, the methods mouseDragged() and mouseMoved() do not have any code - they are just declared in the interface called MouseMotionListener. But if your class needs to react when the mouse is being moved or dragged, such class has to implement this interface. The word implements means that this class will definitely include the methods that might have been declared in this interface (I've used the word might, because some interfaces may not declare any methods), for example:

import java.awt.event.MouseMotionListener;

class myDrawingPad implements MouseMotionListener{

// your code that can draw goes here

mouseDragged(MouseEvent e){
// your code that has to be performed when
// the mouse is being dragged goes here
}
mouseMoved(MouseEvent e){
// your code that has to be performed when
// the mouse is being moved goes here
}
}
You may be wondering, why even bother creating interfaces without writing the code in its methods? The reason is that once the interface is created, it could be reused by many classes. For example, when other classes (or JVM itself) see that the class myDrawingPad implements the interface MouseMotionListener, they know for sure that this class will definitely have methods mouseDragged() and mouseMoved(). Every time when a user moves the mouse, JVM will call the method mouseMoved()and execute the code that you wrote in the class that implements this interface. Imagine if a programmer Joe decides to name such a method mouseMoved(), Mary calls it movedMouse(), and Pete prefers mouseCrawling()? In this case the JVM would be confused and wouldn't know which method to call on your class to signal about the mouse movement.

A Java class can implement multiple interfaces, for example it may need to respond to mouse movements as well as to a button click:


class myDrawingProgram implements
MouseMotionListener, ActionListener {

//You have to write the code for each method that
// has been defined in both interfaces here

}
The actionListener will take care of the button clicks, while the MouseMothionListener will deal with the mouse movements.

After getting comfortable with the interfaces that come with Java, you'll be able to create your own interfaces, and you can read more about it in my article "Are you Using Abstract Classes and Interfaces" http://java.sys-con.com/read/37695.htm.

Action Listener

Let's get back to our calculator from the Swing Basics lesson. Modify the class Calculator.java to add the buttons +, -, /, and *. Add these buttons to the panel p2, and place the panel in the East area of the content pane.

Now we'll create another class-listener that will react when the user clicks on one of the buttons. Actually, we could have added the code processing click events to the class Calculator.java itself, but it's better to keep visual and processing parts (the business logic) in separate classes.

We'll name a second class CalculatorEngine, and it must implement a java.awt.ActionListener interface that declares only one method - actionPerformed(ActionEvent). JVM calls this method on the class that implements this interface whenever the user clicks on the button. Create the following simple class:


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

}

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.


@ThingsExpo Stories
"We've been engaging with a lot of customers including Panasonic, we've been involved with Cisco and now we're working with the U.S. government - the Department of Homeland Security," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, will examine the regulations and provide insight on how it affects technology, challenges the established rules and will usher in new levels of diligence...
The financial services market is one of the most data-driven industries in the world, yet it’s bogged down by legacy CPU technologies that simply can’t keep up with the task of querying and visualizing billions of records. In his session at 20th Cloud Expo, Karthik Lalithraj, a Principal Solutions Architect at Kinetica, discussed how the advent of advanced in-database analytics on the GPU makes it possible to run sophisticated data science workloads on the same database that is housing the rich...
"DX encompasses the continuing technology revolution, and is addressing society's most important issues throughout the entire $78 trillion 21st-century global economy," said Roger Strukhoff, Conference Chair. "DX World Expo has organized these issues along 10 tracks with more than 150 of the world's top speakers coming to Istanbul to help change the world."
DX World EXPO, LLC., a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
SYS-CON Events announced today that Massive Networks will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
"The Striim platform is a full end-to-end streaming integration and analytics platform that is middleware that covers a lot of different use cases," explained Steve Wilkes, Founder and CTO at Striim, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that Calligo, an innovative cloud service provider offering mid-sized companies the highest levels of data privacy and security, has been named "Bronze Sponsor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Calligo offers unparalleled application performance guarantees, commercial flexibility and a personalised support service from its globally located cloud plat...
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution and join Akvelon expert and IoT industry leader, Sergey Grebnov, in his session at @ThingsExpo, for an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
While the focus and objectives of IoT initiatives are many and diverse, they all share a few common attributes, and one of those is the network. Commonly, that network includes the Internet, over which there isn't any real control for performance and availability. Or is there? The current state of the art for Big Data analytics, as applied to network telemetry, offers new opportunities for improving and assuring operational integrity. In his session at @ThingsExpo, Jim Frey, Vice President of S...
"We provide IoT solutions. We provide the most compatible solutions for many applications. Our solutions are industry agnostic and also protocol agnostic," explained Richard Han, Head of Sales and Marketing and Engineering at Systena America, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"We are focused on SAP running in the clouds, to make this super easy because we believe in the tremendous value of those powerful worlds - SAP and the cloud," explained Frank Stienhans, CTO of Ocean9, Inc., in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"MobiDev is a Ukraine-based software development company. We do mobile development, and we're specialists in that. But we do full stack software development for entrepreneurs, for emerging companies, and for enterprise ventures," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...
SYS-CON Events announced today that EnterpriseTech has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. EnterpriseTech is a professional resource for news and intelligence covering the migration of high-end technologies into the enterprise and business-IT industry, with a special focus on high-tech solutions in new product development, workload management, increased effic...
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...