What are events in java

How to declare and consume events in Java

Delegation Event Model A mechanism for controlling the events and deciding what should happen after an event occur is referred to as event handling. Management of registered listeners and event firing can be abstracted to some kind of abstract event listener management class.

How to declare and consume events in Java

I have a simple class — will call it Animal. I’d like to fire off an event in the Animal class and have it handled in the class where I instantiated the Animal class. In the event handler, I want to pass an Integer value

How do I pull off something simple like that?

Assuming that the integer being passed is part of the Animal class state, an idiomatic way to do this rather than writing lots of your own code is to fire a PropertyChangeEvent . You can use the PropertyChangeSupport class to do this, reducing your code to this:

public class Animal < // Create PropertyChangeSupport to manage listeners and fire events. private final PropertyChangeSupport support = new PropertyChangeSupport(this); private int foo; // Provide delegating methods to add / remove listeners to / from the support class. public void addPropertyChangeListener(PropertyChangeListener l) < support.addPropertyChangeListener(l); >public void removePropertyChangeListener(PropertyChangeListener l) < support.removePropertyChangeListener(l); >// Simple example of how to fire an event when the value of 'foo' is changed. protected void setFoo(int foo) < if (this.foo != foo) < // Remember previous value, assign new value and then fire event. int oldFoo = this.foo; this.foo = foo; support.firePropertyChange("foo", oldFoo, this.foo); >> > 

Finally, I would advise against using Observer / Observable as it makes code unreadable / difficult to follow: You are constantly having to check the type of the argument passed to the Observer using instanceof before downcasting it, and it’s difficult to see what type of event a specific Observer implementation is expecting by looking at its interface definition. Much nicer to define specific listener implementations and events to avoid this.

Читайте также:  Php ajax load pages

When you want to avoid inheriting from a java.util.Observable-like base class, use an interface and let your observables implement or delegate the interface’s methods.

Here is the observable interface:

public interface IObservable

Here is a helper class that could be used by your real observables:

import java.util.ArrayList; import java.util.List; public class Observable implements IObservable < private Listobservers; @Override public synchronized void addObserver(IObserver o) < if (observers == null) < observers = new ArrayList(); > else if (observers.contains(o)) < return; >observers.add(o); > @Override public synchronized void deleteObserver(IObserver o) < if (observers == null) < return; >int idx = observers.indexOf(o); if (idx != -1) < observers.remove(idx); >> @Override public synchronized void notifyObservers(INotification notification) < if (observers == null) < return; >for (IObserver o : observers) < o.update(notification); >> > 

A real observable could look like this:

class Person implements IObservable < private final IObservable observable = new Observable(); @Override public void setFirstName(String firstName) throws Exception < if (firstName == null || firstName.isEmpty()) < throw new Exception("First name not set"); >this.firstName = firstName; notifyObservers(new Notification(this, getFirstNamePropertyId())); > @Override public void addObserver(IObserver o) < observable.addObserver(o); >@Override public void deleteObserver(IObserver o) < observable.deleteObserver(o); >@Override public void notifyObservers(INotification notification) < observable.notifyObservers(notification); >private static final String FIRSTNAME_PROPERTY_ID = "Person.FirstName"; @Override public String getFirstNamePropertyId() < return FIRSTNAME_PROPERTY_ID; >> 

Here is the observer interface:

public interface IObserver

Finally, here is the notification interface and a basic implementation:

public interface INotification < Object getObject(); Object getPropertyId(); >public class Notification implements INotification < private final Object object; private final Object propertyId; public Notification(Object object, Object propertyId) < this.object = object; this.propertyId = propertyId; >@Override public Object getObject() < return object; >@Override public Object getPropertyId() < return propertyId; >> 

A simple event interface looks like this:

public interface AnimalListener

Animal needs to manage its listeners:

public class Animal < private final ListanimalListeners = new ArrayList() public void addAnimalListener(AnimalListener animalListener) < animalListeners.add(animalListener); >> 

Your Animal -creating class needs to do this:

public class AnimalCreator implements AnimalListener < public void createAnimal() < Animal animal = new Animal(); animal.addAnimalListener(this); // implement addListener in An >public void animalDoesSomething(int action) < System.ot.println("Holy crap, animal did something!"); >> 

Now Animal can fire events.

That looks like a lot of code for something as simple as “firing events” but maybe firing events isn’t simple at all. 🙂

Of course there are various extensions to this simple mechanism.

  • I always make my event listeners extend java.util.EventListener .
  • The first parameter for each listener method should be the source of the event, i.e. public void animalDoesSomething(Animal animal, int action); .
  • Management of registered listeners and event firing can be abstracted to some kind of abstract event listener management class. Look at PropertyChangeSupport to know what I mean.

EDIT: Adamski’s PropertyChangeSupport based approach seems better Observable one that I suggested.

Delegation Event Model in Java, Delegation Event Model in Java. The Delegation Event model is defined to handle events in GUI programming languages.The GUI stands for Graphical User …

Event notification in Java

In java, I feed very confused on observer pattern or JMS. I want to use the event notification like below. Let us forget about those JMS or Observer , do you think it is possible or doable ? if yes, how to complete it ?

newSalesOrder = new SalesOrder(); newSalesOrder.notified("new SalesOrder order Delivery.class); EventRegister.bindEvent(SalesOrder.class, Warehouse.class); //////////// Delivery delivery = new Delivery(); delivery.listerning(new Event(source) < if(source == SalesOrder.class)< >>); ////////// Warehouse warehouse = new Warehouse(); warehouse.listerning(new Event(source) < if(source == SalesOrder.class)< >>); /////////// EventRegister < static bindEvent(Class source, Class destination)< //. >> 

You need to register (bind) objects not classes. You can keep registration list static at EventRegister but I think it’s better to keep them as instance at SalesOrder. So it would be:

import java.util.ArrayList; import java.util.List; public class Test < public static void main(String[] args) < SalesOrder mySalesOrder = new SalesOrder(); Warehouse myWarehouse = new Warehouse(); mySalesOrder.addListener(myWarehouse); Delivery myDelivery = new Delivery(); mySalesOrder.addListener(myDelivery); Event myEvent = new Event(); // Now 'myDelivery' and 'myWarehouse' objects will receive 'myEvent' // object on their 'onEvent(Event event)' method System.out.println("Event to be published: " + myEvent); mySalesOrder.publishEvent(myEvent); >> interface Listener < public void onEvent(Event event); >class Event < // Add reqired detail here! >class SalesOrder < private Listlisteners = new ArrayList(); public void addListener(Listener listener) < listeners.add(listener); >public void removeListener(Listener listener) < listeners.remove(listener); >// Use proper access modifier public void publishEvent(Event event) < System.out.println(this + " is goint to publish " + event + " to " + listeners + " listeners."); for (Listener listener : listeners) < listener.onEvent(event); >> // . > class Warehouse implements Listener < public void onEvent(Event event) < // Do something when event received System.out.println(event + " received at " + this); >// . > class Delivery implements Listener < public void onEvent(Event event) < // Do something when event received System.out.println(event + " received at " + this); >// . > 

If you run it it will print something like:

Event to be published: Event@190d11

SalesOrder@a90653 is goint to publish Event@190d11 to [Warehouse@de6ced, Delivery@c17164] listeners.

Event@190d11 received at Warehouse@de6ced

Event@190d11 received at Delivery@c17164

This is a trivial sample, in real life use cases you may consider using a thread-safe implementation and refactoring registration out of SalesOrder using composition or inheritance.

AWT AWTEvent Class, It is the root event class for all AWT events. This class and its subclasses supercede the original java.awt.Event class. This class is defined in java.awt …

Types of events in Java

An event is one of the most important concepts in Java. The change in the state of an object or behavior by performing actions is referred to as an Event in Java. Actions include button click, keypress, page scrolling, or cursor movement.

Java provides a package java.awt.event that contains several event classes.

We can classify the events in the following two categories:

Types of events in Java

  1. Foreground Events
  2. Background Events
Foreground Events

Foreground events are those events that require user interaction to generate. In order to generate these foreground events, the user interacts with components in GUI. When a user clicks on a button, moves the cursor, and scrolls the scrollbar, an event will be fired.

Background Events

Background events don’t require any user interaction. These events automatically generate in the background. OS failure, OS interrupts, operation completion, etc., are examples of background events.

Delegation Event Model

A mechanism for controlling the events and deciding what should happen after an event occur is referred to as event handling. Java follows the Delegation Event Model for handling the events.

The Delegation Event Model consists of Source and Listener .

Buttons, checkboxes, list, menu-item, choice, scrollbar, etc., are the sources from which events are generated.

The events which are generated from the source are handled by the listeners. Each and every listener represents interfaces that are responsible for handling events.

To learn more about Delegation Event Model , go through the following link:

We need to register the source with the listener for handling events. Different types of classes provide different registration methods.

The syntax of registering the source with the listener is as follows:

For example, if we need to register Key and Action events, we use the addActionListener() and addKeyListener() methods.

These are some of the most used Event classes:

S.No. Event Class Listener Interface Methods Descriptions
1. ActionEvent ActionListener actionPerformed() ActionEvent indicates that a component-defined action occurred.
2. AdjustmentEvent AdjustmentListener adjustmentValueChanged() Adjustment events occur by an adjustable object like a scrollbar.
3. ComponentEvent ComponentListener componentResized(), componentMoved(), componentShown() and componentHidden() An event occurs when a component moved, changed its visibility or the size changed.
4. ContainerEvent ContainerListener componentRemoved() and componentAdded() The event is fired when a component is added or removed from a container.
5. FocusEvent FocusListener focusLost() and focusGained() Focus events include focus, focusout, focusin, and blur.
6. ItemEvent ItemListener itemStateChanged() Item event occurs when an item is selected.
7. KeyEvent KeyListener keyPressed(), keyReleased(), and keyTyped(). A key event occurs when the user presses a key on the keyboard.
8. MouseEvent MouseListener and MouseMotionListener mouseClicked(), mousePressed(), mouseEntered(), mouseExited() and mouseReleased() are the mouseListener methods. mouseDregged() and mouseMoved() are the MouseMotionListener() methods. A mouse event occurs when the user interacts with the mouse.
9. MouseWheelEvent MouseWheelListener mouseWheelMoved(). MouseWheelEvent occurs when the mouse wheel rotates in a component.
10. TextEvent TextListener textChanged() TextEvent occurs when an object’s text change.
11. WindowEvent WindowListener windowActivated(), windowDeactivated(), windowOpened(), windowClosed(), windowClosing(), windowIconfied() and windowDeiconified(). Window events occur when a window’s status is changed.

Let’s take an example to understand how we can work with the events and listeners:

EventHandlingExample1.java

// import required classes and package, if any package JavaTpoint.Examples; import java.awt.*; import java.awt.event.*; //create class EventHandlingExample1 to perform event handling within the class public class EventHandlingExample1 < // create variables for Frame, Label and Panel private Frame frame; private Label header; private Label status; private Panel panel; // default constructor public EventHandlingExample1()< makeGUI(); >// main() method start public static void main(String[] args) < // create an instance of EventHandlingExample1 EventHandlingExample1 obj = new EventHandlingExample1(); obj.addButtonsAndLabel(); >// create makeGUI() method to create a UI to perform user interaction private void makeGUI() < // initialize Frame frame = new Frame("Event Handling Example"); // set frame size by using setSize() method frame.setSize(400,400); //set frame layout by using setLayout() method frame.setLayout(new GridLayout(3, 1)); // add window listener to frame frame.addWindowListener(new WindowAdapter() < public void windowClosing(WindowEvent windowEvent)< System.exit(0); >>); // initialize header and set alignment to center header = new Label(); header.setAlignment(Label.CENTER); //initialize status and set its alignment and size status = new Label(); status.setAlignment(Label.CENTER); status.setSize(350,100); // initialize panel panel = new Panel(); // set flow layout to panel panel.setLayout(new FlowLayout()); // add header, status and panel to frame frame.add(header); frame.add(panel); frame.add(status); frame.setVisible(true); > // create addButtonsAndLabel() method private void addButtonsAndLabel() < // set label test header.setText("Click a button: "); // create ok, submit and cancel buttons Button okBtn = new Button("OK"); Button submitBtn = new Button("Submit"); Button cancelBtn = new Button("Cancel"); // use setActionCommand() method to set action for ok, submit and cancel buttons okBtn.setActionCommand("OK"); submitBtn.setActionCommand("Submit"); cancelBtn.setActionCommand("Cancel"); // add event listener to buttons using addActionListener() and ButtonClickListener() okBtn.addActionListener(new ButtonClickListener()); submitBtn.addActionListener(new ButtonClickListener()); cancelBtn.addActionListener(new ButtonClickListener()); // add buttons to panel panel.add(okBtn); panel.add(submitBtn); panel.add(cancelBtn); // make frame visible by using setVisible()mmethod frame.setVisible(true); >// implements ActionListener interface private class ButtonClickListener implements ActionListener < // define actionPerformed() method of ActionListener public void actionPerformed(ActionEvent event) < // get action command using getActionCommand() method of Event String command = event.getActionCommand(); // code to check which button is pressed if( command.equals( "OK" )) < status.setText("Ok Button clicked."); >else if( command.equals( "Submit" ) ) < status.setText("Submit Button clicked."); >else < status.setText("Cancel Button clicked."); >> > >

Types of events in Java

Send or receive, EventProcessorHost is a Java class that simplifies receiving events from Event Hubs by managing persistent checkpoints and parallel receives from those Event Hubs. Using EventProcessorHost, you can split events across multiple receivers, even when hosted in different nodes. This example shows how to use …

Источник

What are events in java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

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