---
title: "javaFX学习之FXRobot"
author: "lujin55"
date: "2013-01-10T19:04:22Z"
tags: []
categories: ["编程语言"]
slug: "javafx-fxrobot"
draft: false
lastmod: "2013-01-10T19:04:22Z"
id: 1725763
url: "https://lujin55.iteye.com/blog/1725763"
---

FXRobot通过该类可以模拟键盘事件，一般用于虚拟键盘，相当于手机上的虚拟键盘。

Ctrl+A全选

```java

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。
复制，粘贴等就改成相应的就可以了。

输入值得话

```java

FXRobot robot = FXRobotFactory.createRobot(scene);
robot.keyPress(KeyCode.A);
robot.keyType(KeyCode.A, "A");
robot.keyRelease(KeyCode.A);

```


看个完整例子：模拟全选Ctrl+A组合键

```java

@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();
	}

```