gpt4 book ai didi

java - 如何使用JavaFX KeyListeners?

转载 作者:行者123 更新时间:2023-12-02 04:41:39 24 4
gpt4 key购买 nike

我有一个可编辑的 JavaFX ComboBox。用户必须只能

  1. 输入字母('a' 到 'z')、空格和圆括号('(', ')')以输入字符串
  2. 按 Tab 退出
  3. 按 Enter 键退出

如何过滤掉所有其他键、修饰符等?

我已经阅读并使用了诸如 Key_Pressed、Key_Released 之类的事件处理程序,但我无法找出实现上述目标的直接方法。 我使用的是 Mac OS Yosemite、Java 8、最新版本的 JavaFX 和
public static final EventType<KeyEvent> KEY_TYPED只是根本不起作用。下面的代码是我的尝试。变量 typedText 存储所需的值。

comboBox.addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() {
private final String[] allowedItems = new String[]{"a","b","c","d","e","f",
"g","h","i","j","k","l","m","n","o","p","q","r",
"s","t","u","v","w","x","y","z"," ","(",")"};
private final List data = Arrays.asList(allowedItems);
private String tempInput;
public boolean containsCaseInsensitive(String s, List<String> l){
for (String string : l) {
if (string.equalsIgnoreCase(s)){
return true;
}
}
return false;
}
public void handle(KeyEvent event) {
boolean b;
b = event.isShiftDown();
if (b) {
if (event.getText().equals("(")) {
tempInput = "(";
} else if (event.getText().equals(")")){
tempInput = ")";
}
} else {
tempInput = event.getCode().toString().toLowerCase();
}
System.out.println("tempInput:"+tempInput);
if (containsCaseInsensitive(tempInput, data)) {
typedText = tempInput;
System.out.println("typedText:"+typedText);
}
}
});
}

最佳答案

您可以获取编辑器(在您的情况下是一个 TextField),并向其中添加一个 TextFormatter 以限制输入。

Tab 开箱即用,但“输入”按键是另一回事,我只是在这个示例中请求焦点。通常您会导航到焦点遍历列表中的下一项,但 JavaFX 中还没有面向 future 的 API。

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class ComboBoxSample extends Application {

@Override
public void start(Stage stage) {

ComboBox<String> comboBox = new ComboBox<>();
comboBox.setEditable(true);
comboBox.getItems().addAll("A", "B", "C", "D", "E");
comboBox.setValue("A");


// restrict input
TextField textField = comboBox.getEditor();
TextFormatter<String> formatter = new TextFormatter<String>(change -> {
change.setText(change.getText().replaceAll("[^a-z ()]", ""));
return change;

});
textField.setTextFormatter(formatter);

// dummy textfield to jump to on ENTER press
TextField dummyTextField = new TextField();

comboBox.addEventFilter(KeyEvent.KEY_PRESSED, e -> {
if( e.getCode() == KeyCode.ENTER) {
dummyTextField.requestFocus();
e.consume();
}
});

HBox root = new HBox();

root.getChildren().addAll(comboBox, dummyTextField);

Scene scene = new Scene(root, 450, 250);
stage.setScene(scene);
stage.show();

}

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

}

关于java - 如何使用JavaFX KeyListeners?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30115425/

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