Event and Listener

An Event Listener, once set to an applet object, waits for some action to be performed on it, be it mouse click, mouse hover, pressing of keys, click of button, etc. The class you are using reports the activity to a class set by the class using it. That method then decides on how to react because of that action, usually with a series of if statements to determine which action it was performed on. source.getSource() will return the name of the object that the event was performed on, while the source is the object passed to the function when the action is performed. Every single time the action is performed, it calls the method.

You can find the entire program in Beeper.java. Here is the code that implements the event handling for the button:


public class Beeper ... implements ActionListener {
    ...
    //where initialization occurs:
        button.addActionListener(this);
    ...
    public void actionPerformed(ActionEvent e) {
        ...//Make a beep sound...
    }
}
Event and Listener

The Beeper class implements the ActionListener interface, which contains one method: actionPerformed. Since Beeper implements ActionListenera Beeper object can register as a listener for the action events that buttons fire. Once the Beeper has been registered using the Button addActionListenermethod, the Beeper's actionPerformed method is called every time the button is clicked.

A More Complex Example

The event model, which you saw at its simplest in the preceding example, is quite powerful and flexible. Any number of event listener objects can listen for all kinds of events from any number of event source objects.

Multiple listeners can register to be notified of events of a particular type from a particular source. Also, the same listener can listen to notifications from different objects.
Each event is represented by an object that gives information about the event and identifies the event source. Event sources are often components or models, but other kinds of objects can also be event sources.
Whenever you want to detect events from a particular component, first check the how-to section for that component. A list of the component how-to sections is here. The how-to sections give examples of handling the events that you are most likely to care about. In How to Use Color Choosers, for instance, you will find an example of writing a change listener to track when the color changes in the color chooser.

Using Event Listener in Java

In Java Code, attaching to any event works roughly the same way. Let's take the OnClickListener as an example. First, you need a reference to the view and then you need to use the set method associated with that listener and pass in a class implementing a particular interface


    Button btnExample = (Button) findViewById(R.id.btnExample);
btnExample.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Do something here	
    }
});
    
Alternatively, it is sometimes useful to have your class implement the listener directly, in which case you would add the listener implementation to your class and pass a reference to your class to the setmethod.

    class MyClass extends Fragment implements View.OnClickListener {

    // Elsewhere in a method in the class that sets up the Button ...
        Button btnExample = (Button) findViewById(R.id.btnExample);
        btnExample..setOnClickListener(this);

    @Override
    public void onClick(View v) {
        // Do something here	
    }
}
    

ActionListener

ActionListener is an interface that could be implemented in order to determine how a certain event should be handled. When implementing an interface, all methods in that interface should be implemented, ActionListener interface has one method to implement named actionPerformed().

When you compile and run the above code, the message "Hi!!!" will appear when you click on the button.


import java.applet.Applet;
import java.awt.Button;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class EventApplet extends Applet {

    /**
     * Init.
     */
    public void init() {
        Button clickMeButton = new Button("Click me");

        final Applet eventApplet = this;

        ActionListener specificClassToPerformButtonAction = new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                Dialog dialog = new Dialog(getParentFrame(eventApplet), false);
                dialog.setLayout(new FlowLayout());
                dialog.add(new Label("Hi!!!"));
                dialog.pack();
                dialog.setLocation(100, 100);
                dialog.setVisible(true);
            }

            private Frame getParentFrame(Container container) {
                if (container == null) {
                    return null;
                } else if (container instanceof Frame) {
                    return (Frame) container;
                } else {
                    return getParentFrame(container.getParent());
                }

            }
        };
        clickMeButton.addActionListener(specificClassToPerformButtonAction);

        add(clickMeButton);
    }
}

References By: oracle | wikibooks « Next Post » share on :        :  

Love to hear your Views / Guidance / Recommendations on this Post…

Explore the Technology World

Computer Programming Terminologies Computer Programming Terminology is a general word for the group of specialized words or meanings relating to Computer Programming, and also the study of such t ...Read MoreNew features in JDK 12 with IntelliJ IDEADeveloped by JetBrains (formerly known as IntelliJ) ,IntelliJ IDEA is a Java integrated development environment (IDE) for developing computer software. It is av ...Read MoreGoogle Pay API Implementation Demo for AndroidIn this youtube Channel by Android Developers ,Learn how to implement the Google Pay API for Android with just a few lines of code and how it works with your ex ...Read MoreUnit Testing in .NET Core and Azure Devops pipelineUnit testing is a software testing method by which individual units of source code, usage procedures,sets of one or more computer program modules together with ...Read MoreThe mind behind Linux & GIT : Linus TorvaldsLinus Torvalds transformed technology twice — first with the Linux kernel, which helps power the Internet, and again with Git, the source code management ...Read MoreTensorflow and deep learningWith Tensorflow ,deep machine learning transitions from an area of research into mainstream software engineering. ...Read MoreJava program to return all possible permutations from collection of distinct numbersexample of Java program to return all possible permutations from collection of distinct numbers ...Read MoreReal Time Analytics with Spring Application Development FrameworkSpring is the most popular application development framework for enterprise Java.Millions of developers use Spring to build simple, truly portable, fast and fle ...Read MorePath Setting in Java When an application is launched from command prompt Windows OS searches for the executable program in the current working directory. The prompt throws an error ...Read MoreFacebook | whatsapp|Github | Twitter | LinkedIn | Youtube| reddit About | Cookies-Policy | Disclaimer | Site Map | Contact

Call / Visit for New Batch

Services

Why Join Us

  • ➯ Free Demo Classes
  • ➯ No Registration Fee
  • ➯ Interview Questions
  • ➯ Study Materials
  • ➯ Softwares
  • ➯ Aptitude & Reasoning
  • ➯ Placement Assitance

Address

  • MyJava Training Institute ,
  • Plot No.243 , shop No 14 ,
  • Secnd Floor , Zone-II ,
  • M.P.Nagar , Bhopal,
  • Madhya Pradesh ( 462011 )
  • ☎  08871209400 , 7987028543
  • 🌐 www.myjava.in
FacebookGoogle +TwitterYouTube

MyJava - java Training Institute