| By Yakov Fain | Article Rating: |
|
| September 22, 2005 05:15 AM EDT | Reads: |
43,476 |
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:
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:
interface MouseMotionListener {
void mouseDragged(MouseEvent e);
void mouseMoved(MouseEvent e);
}
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.
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
}
}
A Java class can implement multiple interfaces, for example it may need to respond to mouse movements as well as to a button click:
The actionListener will take care of the button clicks, while the MouseMothionListener will deal with the mouse movements.
class myDrawingProgram implements
MouseMotionListener, ActionListener {
//You have to write the code for each method that
// has been defined in both interfaces here
}
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 {
}
Published September 22, 2005 Reads 43,476
Copyright © 2005 Ulitzer, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
Related Stories
- Your First Java Program
- Intro to Object-Oriented Programming with Java
- Methods, Constructors, Overloading and Access Levels
- Java Exceptions
- Java Streams Basics
- Reading Data from the Internet
- Java Serialization
- Teaching Kids Programming: Even Younger Kids Can Learn Java
- Java Basics: Introduction to Java Threads, Part 1
- Java Basics: Introduction to Java Threads, Part 2
- SYS-CON Webcast: Eclipse IDE for Students, Useful Eclipse Tips & Tricks
Related Links
More Stories By Yakov Fain
Yakov Fain is a Managing Director of Farata Systems, consulting, training and product company. He has authored several Java books, dozens of technical articles. SYS-CON Books released his latest co-authored book , Rich Internet Applications with Adobe Flex and Java: Secrets of the Masters in Spring 2007. Sun Microsystems has nominated and awarded Yakov with the title Java Champion. He leads the Princeton Java Users Group. He is an Adobe Certified Flex Instructor. Yakov co-athored the O'Reilly book "Enterprise Application Development with Flex". He twits at twitter.com/yfain.
- Making Big Data into Small Data
- Panopticon Software Partners with QlikTech to Provide Real-Time Visual Data Monitoring and Analysis Dashboards
- Bloomberg Summit to Focus on Future of Enterprise Technology
- Panopticon Software Partners with QlikTech to Provide Real-Time Visual Data Monitoring and Analysis Dashboards
- WSO2 Technology Executives to Present Workshop on WSO2 Integration Platform Discovery
- Research and Markets: Global - The Internet of Things (IoT)
- TIBCO Announces Intent to Acquire LogLogic
- Nastel Technologies Delivers AutoPilot 6.5, the Industry's First Unified Platform to Manage Multiple Middleware Technologies
- Logica Accelerates Real-Time Transformation of Data to Actionable Business Information with StreamInsight™
- WSO2 Technology Executives Bring Workshop on WSO2 Integration Platform Discovery to Paris
- Fujitsu Releases Software Supporting the Utilization of Big Data
- SL Corporation Announces New Monitoring for the IBM® SmartCloud™
- Making Big Data into Small Data
- Panopticon Software Partners with QlikTech to Provide Real-Time Visual Data Monitoring and Analysis Dashboards
- Bloomberg Summit to Focus on Future of Enterprise Technology
- Panopticon Software Partners with QlikTech to Provide Real-Time Visual Data Monitoring and Analysis Dashboards
- WSO2 Technology Executives to Present Workshop on WSO2 Integration Platform Discovery
- Progress Software Demos Advanced Business Rules Control at Gartner Business Process Management Summit
- Research and Markets: Global - The Internet of Things (IoT)
- TIBCO Announces Intent to Acquire LogLogic
- Nastel Technologies Delivers AutoPilot 6.5, the Industry's First Unified Platform to Manage Multiple Middleware Technologies
- Logica Accelerates Real-Time Transformation of Data to Actionable Business Information with StreamInsight™
- New Research Positions UC4 Software as Leader in Magic Quadrant for Data Center Workload Automation
- WSO2 Technology Executives Bring Workshop on WSO2 Integration Platform Discovery to Paris
- Cover Story: Java Gaming - Understanding the Basic Concepts
- The Transformation of DTS in SQL Server 2005
- Java Basics: Processing GUI Events
- SOA World Conference & Expo 2008 East Call for Papers Deadline Feb 22, 2008
- AjaxWord: An Open Source Web Word Processor
- How To Give Your Web Applications A Facelift With WebCharts3D To Make It A Blockbuster
- Java Product Review — Oracle EDA Suite
- Turning Service-Oriented Events into Business Insight
- JAIN/SLEE: EJB for Communications
- Exclusive Q&A with John Goodson, VP & GM of DataDirect Technologies
- ColdFusion Developer's Journal Special "Frameworks" Focus Issue: Mach-II
- Creating a Flashy Monitoring Application
















Ulitzer content is offered under Creative Commons "Attribution Non-Commercial No Derivatives" License.
For any reuse or distribution, you must make clear to others the license terms of this work.
The best way to do this is with a link to this web page.
Any of the above conditions can be waived if you get written permission from Ulitzer, Inc., the copyright holder.
Nothing in this license impairs or restricts the author's moral rights.