嘿所以我正在为一位朋友制作一个随机延迟等自动转换器,但他已经要求我用javafx制作一个用户界面。我说好了,但现在我需要通过按“r”键来切换自动转向器。我的代码如下,我决定选中复选框,以便我可以知道它是否被切换但是我想这样做以便我可以按r检查复选框并再次按下取消选中因此停止自动转换。提前谢谢。
public class MainFrame extends Application {
CheckBox toggleclick;
@Override
public void start(Stage primaryStage) {
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(25, 25, 25, 25));
Text scenetitle = new Text("11.1 CPS Clicker");
scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 30));
grid.add(scenetitle, 0, 0, 2, 1);
CheckBox cb = new CheckBox();
cb.setText("Begin Clicking");
HBox hbBtn = new HBox(10);
hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
hbBtn.getChildren().add(cb);
grid.add(hbBtn, 1, 4);
final Text actiontarget = new Text();
grid.add(actiontarget, 1, 6);
cb.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
while (true) {
try {
Mouse.sendLeftClick();
} catch (AWTException e1) {
e1.printStackTrace();
}
double deviation = 22;
double mean = 90;
int min = 43;
int max = 198;
Random r = new Random();
double randGauss = (r.nextGaussian() * deviation);
long delayPreClamp = Math.round(randGauss + mean);
long delay = (long) MathUtil.clamp(delayPreClamp, min, max);
try {
Thread.sleep(delay);
} catch (InterruptedException e2) {
e2.printStackTrace();
}
}
}
});
Scene scene = new Scene(grid, 325, 250);
primaryStage.setScene(scene);
primaryStage.show();
primaryStage.setTitle("AutoClicker");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
答案 0 :(得分:0)
尝试创建一个新的EventHandler来在按下某个键时定义一个事件,如下所示:
cb.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
if("R".equals(ke.getText().toUpperCase() )) {
if(cb.isSelected()) {
cb.setSelected(false);
} else {
cb.setSelected(true);
}
}
});
ke.getText()返回按下的键的值,如果是R,则选中或取消选中复选框。