About event handling in java

Event Handling in Java: What is that and How Does it Work?

Any program that is graphic user interface or GUI-based, including Java application for Windows, is driven by events. For a program like a Java application to be useful, it is required to provide a response to commands or inputs from the user. Java applications have events to capture user actions. Before we discuss event handling in Java, let’s start by discussing events.

Check out our free courses to get an edge over the competition.

What is an Event?

Events hold the same meaning and importance in every programming language. They are external effects that are controlled by the user, and that make your application behave in line with the pre-defined condition put in place to record its response to different user actions. An event could even be termed as an object that springs to life when a change takes place within the GUI.

Examples of events in Java include typing of characters or text, clicking on a combo box, clicking on a button, or any other action from the user’s side. Any such action triggers an event, which then results in the creation of the event object that is relevant for that event.

Читайте также:  Collection implementation in java

Ads of upGrad blog

For instance, if a user enters some data (user action that triggers an event), the application produces an output by putting out a dialog box or displaying information (event object). These event-related behaviors are a part of the Event Handling Mechanism of Java and are present in the Swing GUI library. It is important to note that the source of every event and the event listener must be linked. If this isn’t the case, the triggering of an event will yield no action.

Explore Our Software Development Free Courses

Check out upGrad’s Java Bootcamp

Why Does a Program or Application Need to be Event Driven?

Before event handling came into the picture, a program had to collect all the user information itself to know what it was doing at a given point in time. This means that after being run or initialized, a program was always in a big repeat loop that was waiting for the user to do something.

So, the program was looking for any action – from the press of a button to slider movement. After it came to know that something has happened from the user’s side, it prepared itself to deliver the appropriate response. This is referred to as polling. Although polling gets the job done, more often than not, it comes across as too unmanageable and time-consuming a task.

If we consider using it for modern-day applications, it doesn’t really fit the requirements. Two primary reasons make polling unsuitable for modern applications – Polling puts all the event-related code inside the big repeat loop, and the interactions that take place inside this location are too complex. Also, polling makes a program enter a never-ending loop, which results in the exhaustion of CPU cycles without any guarantee of action coming from the user.

The Abstract Window Toolkit or AWT has gone ahead and struck association with a different working model for solving the issue discussed above. This new model is event-driven programming. With AWT, there is no need for the program to look out for user-generated events. It is the Java run time that does this job. It intimates the program as soon as an event takes place. It saves a valuable resource from exhaustion and handles user interaction better.

What are Event Handlers in Java and How do They Work?

Let’s now discuss the primary topic that we set out to deal with. How does event handling in Java work?

As mentioned earlier, events are user actions or external effects that make an application behave in a certain way. In Java, AWT components, including textbox, button, and others, are responsible for the generation of events. As soon as an event is generated, the listener handles it and performs the appropriate action.

Event handling in Java comprises four elements. These could even be termed as event handlers.

Get Software Engineering degrees online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

1. Event source : An event source that generates an event is mostly an AWT component. You can run java.awt.component command to learn about components that may or may not have any role in generating events. The components are the subclass of the original source class. Event sources could be anything from text boxes and combo boxes to buttons, and more.

2. Event classes : In Java, these are classes that account for almost every component that has anything to do with the generation of events. These are also called event types. Here are a few of the most common event classes:

  • ActionEvent : This event class or event type represents an event that involves the clicking of a graphical element, such as a button or a list item. The listener related to this class is ActionListener.
  • KeyEvent : This event class represents an event that involves the pressing and releasing of a key. The listener associated with this class is KeyListener.
  • ContainerEvent : This event type represents an event that happens with the GUI container. This class is associated with any event where user action involves the addition or removal of object(s) from the GUI. The related listener for this class is ContainerListener.
  • MouseEvent : This class represents all those events that involve the clicking or pressing of the mouse. The listener for this class is MouseListener.
  • WindowEvent : This event class or type represents events that involve any action related to a window. Closing, activating, or deactivating a window come under this class. The related listener for this class is WindowListener.

3. Event Listeners : These are interfaces of Java that provides various methods that can be used in different implemented classes. The job of event listeners involves listening for events and then processing them appropriately when they take place. Almost every component in Java has a dedicated listener that handles any event that that component generates. ActionListener handles events that involve lists, buttons, text fields, and menus.

In-Demand Software Development Skills

4. Event Adapters : If a program presents too many abstract methods for the listener to override, it can get difficult to compile it. For example, if we want to close a frame, there are seven WindowListener abstract methods that we need to override. To reduce complexity and heavy coding, Java has event adapters. Event adapters are already overridden abstract methods.

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

Conclusion

It is important to remember that multiple event sources and listeners can interact with each other. So, multiple events belonging to the same class can be handled by a single listener. This means that one listener can handle all those events that involve the same components that perform similar actions. On similar lines, a single event could be handled by more than one listener, only if the program’s design allows this.

Ads of upGrad blog

Get in touch with us to learn about an extensive session on event handling in Java. You wouldn’t regret it!

If you’re interested to learn more about Java for web development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Источник

Event Handling in Java

Event Handling in Java

Any change in the state of an existing object is called as an event, event handlers are designed in order to listen to specific events and perform some logical actions accordingly, AWT components can be registered with required listeners listening to user events and then handle events accordingly. In this topic, we are going to learn about Event Handling in Java.

Web development, programming languages, Software testing & others

Syntax

Here is a syntax of how AWT event handlers are used:

// importing awt package import java.awt.*; // create a class extending Frame component class extends Frame implements < // override methods of implemented interface @Override public void () < // do required actions on event happened >()< component.addActionListerner(listenerClassobject); // register component with listener >>

The above syntax shows how to use a listener in java awt.

In the above syntax denotes name of java class. can be the name of listener to be used. In order to register our component to the event, we need to register the component with the listener using the method as shown above.

Event Handling in Java

The following are different types of listeners available in java awt:

Event ListenerInterface Description
ActionEvent ActionListener Produced on click of a button, selection of an item from menu or other.
MouseEvent MouseListener Produced when mouse event takes place like moved, pressed, click, double-click or enter/exit of mouse pointer into a specified area.
KeyEvent KeyListener Produced on the press of the key.
ItemEvent ItemListener Produced when the checkbox is checked or unchecked or item present in a list is clicked.
WindowEvent WindowListener Produced on different operations performed on a window.
ComponentEvent ComponnetEventListener Produced when a component is made visible, hidden, moved or changes are made in component size.
ContainerEvent ContainerListener Produced when a component is inserted or deleted from a container.
FocusEvent FocusListener Produced when a component attains or loses keyboard focus.
AdjustmentEvent AdjustmentListener Produced when changes are made to using the scrollbar.
MouseWheelEvent MouseWheelListener Produced when the mouse wheel is rotated.
TextEvent TextListener Produced whenever there is a change in the value of textarea or textfield.

The following are major steps involved in the handling of an event in java awt:

  • Implement the required interface and override its methods.
  • Register the component with the listener.

Example of Event Handling in Java

The following example shows how to use event handlers in java awt:

package com.edubca.awtdemo; // importing important packages import java.awt.*; import java.awt.event.*; public class EventHandlerDemo < private Frame parentFrame; private Label headerTitle; private Label status; private Panel panel; public EventHandlerDemo()< prepareInterface(); >public static void main(String[] args) < EventHandlerDemo awtdemo = new EventHandlerDemo(); awtdemo.showEventHandlingDemo(); >private void prepareInterface() < parentFrame = new Frame("Java Event Handling Example"); parentFrame.setSize(400,400); parentFrame.setLayout(new GridLayout(3, 1)); parentFrame.addWindowListener(new WindowAdapter() < public void windowClosing(WindowEvent windowEvent)< System.exit(0); >>); headerTitle = new Label(); headerTitle.setAlignment(Label.CENTER); status = new Label(); status.setAlignment(Label.CENTER); status.setSize(350,100); panel = new Panel(); panel.setLayout(new FlowLayout()); parentFrame.add(headerTitle); parentFrame.add(panel); parentFrame.add(status); parentFrame.setVisible(true); > private void showEventHandlingDemo() < headerTitle.setText("Handling Button Click Event"); Button firstButton = new Button("First Button"); Button secondButton = new Button("Second Button"); Button thirdButton = new Button("Third Button"); firstButton.setActionCommand("First Button Clicked"); secondButton.setActionCommand("Second Button Clicked"); thirdButton.setActionCommand("Third Button Clicked"); //registering button with listener firstButton.addActionListener(new ButtonClickEventListener()); //registering button with listener secondButton.addActionListener(new ButtonClickEventListener()); //registering button with listener thirdButton.addActionListener(new ButtonClickEventListener()); panel.add(firstButton); panel.add(secondButton); panel.add(thirdButton); parentFrame.setVisible(true); >// inner class implementing Action Listener private class ButtonClickEventListener implements ActionListener < // overriding method public void actionPerformed(ActionEvent e) < String command = e.getActionCommand(); // do different actions according to different commands if( command.equals( "First Button Clicked" )) < status.setText ("First Button Clicked."); >else if( command.equals( "Second Button Clicked" ) ) < status.setText ("Second Button Clicked."); >else < status.setText ("Third Button Clicked."); >> > >

The above program shows how to use awt event handlers in java. It involves implementing the required listener interface and implementing its methods followed by registering the component with the specified listener.

In the above example we have three buttons and one click of buttons the label in footer changes. After the above program is executed the following window prompts up:

Event Handling in Java output 1

On click of the First button, the following text will be produced below:

Event Handling in Java output 2

On Click of the second button, the following output will be produced:

 output 3

On click of the third button, the following output will be produced:

output 4

Therefore we can see that click events of different buttons is detected by the listener and different functions are then performed accordingly.

Conclusion

The above article provides a clear understanding of event handlers in java awt.

This is a guide to Event Handling in Java. Here we discuss the introduction to Event Handling in Java along with the syntax and examples. You may also have a look at the following articles to learn more –

500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access

1000+ Hours of HD Videos
43 Learning Paths
250+ Courses
Verifiable Certificate of Completion
Lifetime Access

1500+ Hour of HD Videos
80 Learning Paths
360+ Courses
Verifiable Certificate of Completion
Lifetime Access

3000+ Hours of HD Videos
149 Learning Paths
600+ Courses
Verifiable Certificate of Completion
Lifetime Access

All in One Software Development Bundle 3000+ Hours of HD Videos | 149 Learning Paths | 600+ Courses | Verifiable Certificate of Completion | Lifetime Access

Financial Analyst Masters Training Program 1000+ Hours of HD Videos | 43 Learning Paths | 250+ Courses | Verifiable Certificate of Completion | Lifetime Access

Источник

Оцените статью