package sample;
import java.awt.Point; import java.util.LinkedList;
import javafx.application.Application; import
javafx.geometry.Point2D; import
javafx.geometry.Pos; import javafx.scene.Scene;
import javafx.scene.control.Button; import
javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.VBox; import
javafx.scene.paint.Color; import javafx.scene.robot.Robot; import javafx.stage.Stage;
public class Main extends Application {
/**
* 内部类,将每次鼠标的行为以及坐标记录下来
*/
class MyMouseEvent {
// 鼠标行为
MouseButton mb;
// 坐标
public Point2D point2D;
// MIDDLE代表鼠标中键
public static final MouseButton MIDDLE = MouseButton.MIDDLE;
public MyMouseEvent(MouseButton mb, Point2D point2D) {
this.mb = mb;
this.point2D = point2D;
}
}
@Override
public void start(Stage stage) throws Exception {
// 创建面板
VBox pane = new VBox();
// 对齐方式
pane.setAlignment(Pos.TOP_LEFT);
// robot关键对象
Robot robot = new Robot();
// 记录鼠标行为
LinkedList<MyMouseEvent> list = new LinkedList<>();
// 开始
Button beginb = new Button("开始");
beginb.setStyle("-fx-text-fill: red");
// 结束
Button endb = new Button("结束");
endb.setStyle("-fx-text-fill: red");
pane.getChildren().addAll(beginb, endb);
// 点击“开始”按钮时,鼠标行为储存进列表
beginb.setOnAction(e -> {
pane.setOnMouseDragged(m -> {
list.add(new MyMouseEvent(m.getButton(), new Point2D(m.getSceneX(), m.getSceneY())));
});
pane.setOnMousePressed(m -> {
list.add(new MyMouseEvent(m.getButton(), new Point2D(m.getSceneX(), m.getSceneY())));
});
pane.setOnMouseReleased(m -> {
list.add(new MyMouseEvent(m.getButton(), new Point2D(m.getSceneX(), m.getSceneY())));
});
// 针对鼠标中键的滚轮事件
pane.setOnScroll(s -> {
// 判断是否为鼠标中键滚轮事件
if (s.getButton() == MyMouseEvent.MIDDLE) {
double deltaY = s.getDeltaY();
System.out.println("滚轮事件:deltaY = " + deltaY);
}
});
});
// 点击“结束”按钮时,鼠标行为储存进列表
endb.setOnAction(e -> {
for (MyMouseEvent m : list) {
// 判断是否为鼠标中键按动事件
if (m.mb == MyMouseEvent.MIDDLE) {
System.out.println("中键按动事件:(" + m.point2D.getX() + ", " + m.point2D.getY() + ")");
} else {
System.out.println("鼠标" + m.mb.toString() + ":" + "(" + m.point2D.getX() + ", " + m.point2D.getY()
+ ")");
}
}
});
Scene scene = new Scene(pane, 500, 500);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}