gpt4 book ai didi

java - 如何在 JavaFX 中使用 KeyCombination 获取用户输入?

转载 作者:行者123 更新时间:2023-11-30 06:14:57 24 4
gpt4 key购买 nike

我正在开发一个简单的修复内到修复后转换器。我想从键盘获取用户的输入。要输入一些符号,例如“+”,用户必须按 Shift 键。我正在使用 KeyCombination 对象来捕获用户是否正在使用 Shift。

我的代码一直给我这个错误:键代码必须与修饰键不匹配!

但是,当我查看键码时,它不是 Shift,而是按下的任何数字行键。例如,如果用户按 Shift + =,则键码为 EQUALS,而不是 Shift_DOWN 修饰符。该代码按预期工作,但我不知道如何消除此异常。

tfInput.setOnKeyPressed(e -> {

if (e.isShiftDown()) {
KeyCombination kc = new KeyCodeCombination(e.getCode(),
KeyCombination.SHIFT_DOWN);
userInput = kc.toString();
}

最佳答案

您收到错误的原因是因为组合键中的第一个参数是键码,而 Shift 是键修饰符,您可以通过在继续之前检查该键是否为 SHIFT 来停止收到此错误

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.stage.Stage;

public class Main extends Application {

private String userInput;

@Override
public void start(Stage stage) {
TextField textField = new TextField();

textField.setOnKeyPressed(e -> {
System.out.println(e.getCode());
if (e.isShiftDown()&&!e.getCode().toString().equals("SHIFT")) {
KeyCombination kc = new KeyCodeCombination(e.getCode(), KeyCombination.CONTROL_ANY);
userInput = kc.toString();
System.out.println(userInput);
}
});

Scene scene = new Scene(textField);
stage = new Stage();
stage.setScene(scene);
stage.show();
}

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

关于java - 如何在 JavaFX 中使用 KeyCombination 获取用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49434353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com