javaFX学习之FXRobot

  FXRobot通过该类可以模拟键盘事件,一般用于虚拟键盘,相当于手机上的虚拟键盘。

Ctrl+A全选
FXRobot robot = FXRobotFactory.createRobot(scene);
robot.keyPress(KeyCode.CONTROL);
robot.keyPress(KeyCode.A);
robot.keyType(KeyCode.A, "");
robot.keyRelease(KeyCode.A);
robot.keyRelease(KeyCode.CONTROL);

要按顺序,Ctrl,A,A,Ctrl。
复制,粘贴等就改成相应的就可以了。

输入值得话
FXRobot robot = FXRobotFactory.createRobot(scene);
robot.keyPress(KeyCode.A);
robot.keyType(KeyCode.A, "A");
robot.keyRelease(KeyCode.A);


看个完整例子:模拟全选Ctrl+A组合键
@Override
	public void start(Stage stage) throws Exception {
		Group group = new Group();
		
		final TextField tf = new TextField();
		group.getChildren().add(tf);
		Scene scene = new Scene(group,600,500);
		Button button = new Button("Ctrl+A");
		button.setLayoutY(100);
		group.getChildren().add(button);
		final FXRobot robot = FXRobotFactory.createRobot(scene);
		button.setOnAction(new EventHandler<ActionEvent>(){

			@Override
			public void handle(ActionEvent arg0) {
				tf.requestFocus();
				robot.keyPress(KeyCode.CONTROL);
				robot.keyPress(KeyCode.A);
				robot.keyType(KeyCode.A, "");
				robot.keyRelease(KeyCode.A);
				robot.keyRelease(KeyCode.CONTROL);
			}
		});
		stage.setScene(scene);
		stage.show();
	}

你可能感兴趣的:(JavaFX,虚拟键盘)