Updated April 4, 2023
Introduction to JavaFX Event
Using JavaFX, several types of applications such as desktop, web, and graphical applications can be developed. Most of the applications in the current world need user interaction to work. For that, the event concept is used from JavaFX. An event is said to have happened in the situations where the user interacts with the application nodes. These events can be triggered using mouse movements, button press, page scrolling, etc. That is, these events are able to give a notification that something has happened from the user end.
Syntax of JavaFX Event
There are several events that JavaFX supports. For Event class, the package used is javafx.event which is considered as the base class.
Following are the different types of events supported by JavaFX:
1. MouseEvent: This event occurs in the situation where the mouse is clicked.
- Represented Class: MouseEvent.
- Actions: Clicking mouse, pressing the mouse, releasing the mouse, moving mouse, target entering, target exiting etc.
Syntax:
EventHandler<MouseEvent> eh = new EventHandler<MouseEvent>()
2. KeyEvent: This event occurs in the situation where a keystroke happens at the node.
- Represented Class: KeyEvent.
- Actions: Typing key, pressing a key, releasing the key.
Syntax:
EventHandler<KeyEvent> eh = new EventHandler<KeyEvent>()
3. DragEvent: This event occurs in the situation where dragging of the mouse is done.
- Represented Class: DragEvent.
- Actions: Entering drag, dropping drag, entering target, exiting target, drag over.
Syntax:
EventHandler<DragEvent> eh = new EventHandler<DragEvent>()
4. WindowEvent: This event occurs in the situation where a keystroke happens at the node.
- Represented Class: WindowEvent.
- Actions: Hiding window, showing window.
Syntax:
EventHandler<WindowEvent> eh = new EventHandler<WindowEvent>()
How JavaFX Event Handling works?
- Event Handling is the process in which the decision to determine what has to have happened when an event occurs and how to control that particular event.
- For this, a code is used as an event handler that gets executed at the time which the event has occurred.
- JavaFX offers several handlers as well as filters for handling the events.
- That is, for every event in JavaFX, it has a target which is the node where the event has occurred (these nodes can be scene, window, or node), a source where the event has generated (mouse, keys, etc.), type of the event (mouse event, key event, etc.).
Constructors of JavaFX Event
Given below are the two constructors of the JavaFX event:
- Event(EventType<? extends Event> type): A new event will be constructed using the mentioned type of event.
- Event(Objectsrc, EventTarget t, EventType<? extends Event> type): A new event will be constructed using the mentioned type of event, source and target.
Methods of JavaFX Event
Given below are the different methods:
- clone(): A copy of the event will be created and returned.
- consume(): Notes the event as consumed.
- getEventType(): Type of the event will be returned.
- getTarget(): Target of the event will be returned.
- isConsumed(): Checks the event is consumed using any filter or handler.
- copyFor(Objectsrc, EventTarget target): A copy of the event will be created and returned with the source and target mentioned.
- fireEvent(EventTargettrgt, Event ev): Mentioned event will be fired.
Example of JavaFX Event
Given below is the sample program of the event handler in JavaFX:
JavaFX program to demonstrate the event handling.
Code:
// javafx program to demonstrate the event handling
//import the necessary classes
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
//main class that extends the Appication
public class EventProgramSample extends Application{
@Override
//starts...
public void start(Stage st) throws Exception {
//create a circle by providing the dimensions
Circle crc = new Circle(150,150,60);
//fill the circle with red color
crc.setFill(Color.RED);
//set a stroke using green color
crc.setStroke(Color.GREEN);
//create a button by providing the text as 'click TO PLAY'
Button buttn = new Button("Click TO PLAY");
//set the x coordinate
buttn.setTranslateX(120);
//set the y coordinate
buttn.setTranslateY(200);
//create a button by providing the text as 'wait'
Button btn1 = new Button("wait..");
//set the x coordinate
btn1.setTranslateX(176);
//set the y coordinate
btn1.setTranslateY(220);
//For creating the animation, TranslateTransition class is instantiated
TranslateTransition tobj = new TranslateTransition();
//set the attributes for the class TranslateTransition
tobj.setAutoReverse(true);
//x value
tobj.setByX(220);
//set the cycle count
tobj.setCycleCount(120);
//set the duration
tobj.setDuration(Duration.millis(600));
//set the node
tobj.setNode(crc);
//Create an EventHandler
EventHandler<MouseEvent> hd = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent ev) {
// TODO Auto-generated method stub
//condition checked where the event source is equal to button
if(ev.getSource()==buttn)
{
//on clicking the first button, animation strts
tobj.play();
}
//condition checked where the event source is equal to button of wait
if(ev.getSource()==btn1)
{
//on clicking the wait button, animation pauses
tobj.pause();
}
//consume the event
ev.consume();
}
};
//Add a play button Handler
buttn.setOnMouseClicked(hd);
//Add a wait button handler
btn1.setOnMouseClicked(hd) ;
//Create a Group
Group gp = new Group() ;
//add everything to the group
gp.getChildren().addAll(crc,buttn,btn1) ;
//create a scene
Scene sc = new Scene(gp,430,320,Color.BLUE) ;
//set the scene
st.setScene(sc);
//set the title
st.setTitle("Sample on EvenetHandler");
//display the result
st.show();
}
//main method
public static void main(String[] args) {
//launch the application
launch(args);
}
}
Output:
First, import all the necessary classes. Then, create a circle by mentioning the size, color etc. Once this is done, create two buttons- one for playing the animation and the other for stopping the same. Moreover, the two different buttons are registered by the one event handler. But, the point is they are discriminated against by the method handle(). The movement of the circle starts by clicking the play button, and the direction of movement will be in the X direction, as shown below. By comparing both the above and below figures, it is possible to identify that the position of the circle has changed. That means the program has worked successfully.
Conclusion
JavaFX offers different types of applications such as desktop, web, and graphical applications. As user interaction is one of the major steps in the applications, certain event handlers are used. In this article, different aspects such as syntax, types, constructors, methods, working, and examples of an event in JavaFX is given.
Recommended Articles
This is a guide to JavaFX Event. Here we discuss the introduction, how JavaFX event handling works? constructors, methods and example. You may also have a look at the following articles to learn more –