Tuesday, 13 October 2015

Tutorial On Mouse Event In JavaFx

Java fx provides various mouse events,in this tutorials I have used several  mouse events  to explain how to use mouse events in javafx,they are simple and easy to use.Following are the mouse event used in this tutorial.

MOUSE_CLICKED IN JAVAFX:

This event is used to detect the mouse clicked by user.This event provide button like behaviour to a node.

MOUSE_ENTERED_TARGET IN JAVAFX:

This event is occurs when mouse enter in the region of node.

MOUSE_DRAGED IN JAVAFX:

In this example we have used this event for dragging a button this event is used to detects the drag by a user on  a node.

CODING:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;


public class mainfx extends Application
{


@Override
public void start(Stage primaryStage)
{

StackPane root = new StackPane();

Button btn = new Button();

btn.setText("BUTTON");


btn.setOnMouseClicked((MouseEvent)->
{
System.out.println("Mouse clicked");
}
);
btn.setOnMouseEntered((MouseEvent)->
{
System.out.println("Mouse Entered");
}
);
btn.setOnMouseExited((MouseEvent)->
{
System.out.println("Mouse Exit");
}
);
btn.setOnMouseReleased((MouseEvent)->
{
System.out.println("Mouse Release");
}
);
btn.setOnMouseDragged((MouseEvent me)->
{
double x = me.getX();
double y = me.getY();
btn.setTranslateX(x);
btn.setTranslateY(y);
}
);

root.getChildren().add(btn);


Scene scene = new Scene(root, 300, 250);

primaryStage.setTitle("Mouse Event");
primaryStage.setScene(scene);
primaryStage.show();
}


public static void main(String[] args) {
launch(args);
}

}

No comments:

Post a Comment