What is the difference between MouseEvent, ActionEvent and Event in JavaFX?

faraaz :

I am new to JavaFX and see that there are different types of event handlers. What is the difference between MouseEvent, ActionEvent and Event in JavaFX?

jewelsea :

Event is the superclass of all event types.

Sample event types are:

  • KeyEvents which are generated when a key is pressed.
  • MouseEvents that are generated by a mouse interaction like a move or button click.
  • There are many more.

Events don't have to only be generated by the JavaFX system. You can emit and consume your own custom events if you wish, but, usually, most events are generated by the JavaFX system.

An ActionEvent is a kind of event which often makes it easier to code to and respond to something being activated.

Often multiple events will be generated for a single action. For example, if you click on a button with a mouse you could get MOUSE_PRESSED, MOUSE_RELEASED and MOUSE_CLICKED events in addition to an ActionEvent.

If you wanted to respond to the button activation, you could listen for a MOUSE_CLICKED event, however that would not be recommended. This is because there are other ways to activate a button or the button could be disabled in which case you wouldn't want to take action on it. If it is a default button, the ENTER key can trigger the button, or the user could activate the button by pressing SPACE when they are focused on the button. When the button is activated by the keyboard, then there is no associated mouse event, so listening to mouse events for mouse activation is not recommended. Usually, you just want to know that the button was activated and not what caused it and you don't want to monitor all event types yourself that could cause the activation and under what conditions that activation should actually occur when the event triggers.

JavaFX provides the ActionEvent which will be emitted whenever the button is activated, regardless of the method that was used to activate it. This makes it much easier for you to code, as all you need to write is button.setOnAction(event -> handleButtonAction());.

An ActionEvent is also used in many places where it didn't seem worthwhile or necessary to create a specific type of event, for example in an animation KeyFrame when the key frame is activated. So ActionEvents aren't just used to handle button events, but may be used in many places.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=471834&siteId=1