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

Now compile the project and run the class Calculator. It works almost the same as the real world calculators.

Congratulations! Your first calculator is ready, give it as a gift to your friends.

Some Other Event Listeners

These are some other Java listeners from the package java.awt that are good to know:

  • Focus listener will send a signal to your class when a component gains or loses focus. For example, we say that the text field has focus, if it has a blinking cursor.
  • Item listener reacts on selection of items in a list or a combobox (dropdown box).
  • Key listener responds to keyboard buttons.
  • Mouse listener responds when mouse is clicked, or enters/leaves a component's area on the window.
  • Mouse movement listener tells you if the mouse is being moved or dragged.
  • Window listener gives you a chance to catch the moments when the user opens, closes, minimizes or activates the window.
In the next table you'll see the name of the listener interfaces, and the methods that these interfaces declare.


For example, the FocusListener interface declares two methods: focusGained() and focusLost(). This means that even if your class is interested only in processing of the events when a particular field gains the focus, you also must include the empty method focusLost(). This may be annoying, and Java provides special adapter classes for each listener to make the event processing easier.

How to Use Adapters

Let's say you need to save some data on the disk when the user closes the window. According to the table above, the class that implements WindowsListener interface has to include seven methods. This means that you'll have write code in the method windowClosing() and also include six empty methods.

The package java.awt comes with so called adapters, which are classes that have already implemented all required methods (these methods are empty inside). One of such classes is called WindowAdapter. If your class has to process window events, you can extend this class from WindowAdapter and just override the methods you are interested in, for example the method windowClosing().


class MyEventProcessor extends java.awt.WindowsAdapter {
public void windowClosing(WindowEvent e) {
// your code that saves the data on a disk
// goes here.
}
}
The rest is easy - just register this class as an event listener inyou're your window's class:

MyEventProcessor myListener = new MyEventProcessor();
addWindowListener(myListener);
We can achieve the same result using so-called anonymous inner classes, but this topic deserves a separate explanation.

Using Threads with Swing

What if more than one thread needs to access the same Swing component? You may remember from the lesson on threads http://java.sys-con.com/read/48043.htm , that to make an application thread-safe, you should use synchronization, which unfortunately slows down the processing. Swing designers found another solution: all components have to be accessed from a single event-dispatch thread. Let's say on button click you start a thread that will perform some business calculation, and when they are finished, it need to display the result in a text field on the screen. What it at the same time the user decides to click on the same text field? Do you smell the deadlock here? So instead of accessing the text field directly from your thread or the actionPerformed() method, just add it to the Swing's EventQueue, that will pass the result of your calculations to the event-dispatch thread, which in turn will update the text field in a thread-safe way.

Technically, it's done with a help of the class javax.swing.SwingUtilities and its method invokeLater(). You need to pass to this method an object that implements Runnable interface and put your business code in method run() of such object. You can simply use an anonymous class to create such object on the fly (I'll cover anonymous classes in one of the future articles). For example, if a user need to start some process on a click of a button, it may look like this:


public void actionPerformed(ActionEvent e){

javax.swing.SwingUtilities.invokeLater(
new Runnable(){ // Anonymous class creation
public void run(){
// your business code goes here
// followed by update of the text in the text field
}
}
)
}
Calling the static method invokeLater() insures, that the request to update the text field will be placed in the event queue to avoid potential clashes with other competing threads.

Is this a must to program Swing event processing this way? Well, it's highly advisable.

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.