如何使用JavaFX KeyListeners?

时间:2015-05-08 03:46:12

标签: java javafx keylistener

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

  1. 输入字母('a'到'z'),空格和圆括号('(',')')输入字符串
  2. 按Tab键退出
  3. 按enter退出
  4. 如何过滤掉所有其他键,修饰符等?

    我已经阅读并使用了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);
                } 
            }
        });
    }
    

1 个答案:

答案 0 :(得分:1)

您可以获取编辑器,它是您的案例中的TextField,并向其添加TextFormatter,从而限制输入。

选项卡开箱即用,但“输入”按键是另一回事,我只是请求此示例中的焦点。通常你会导航到焦点遍历列表中的下一个项目,但是在JavaFX中还没有面向未来的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);
    }

}