0

I used jnativehook for global keyboard listening. I created GUI in JavaFX 11. I have a TextField to define name of a file created after pressing specified key combination.

The problem is I cannot edit text in the TextField by keyboard. I can delete or paste text by mouse but not by keyboard.

I created an individual thread for global keyboard listening. My idea was to stop this thread when the TextField is focused. Unfortunately, my attempts failed.

Here is a minimimal reproducible example which causes similar problem:

Main.java

public class Main extends Application {
private static final int APP_WIDTH = 400;
private static final int APP_HEIGHT = 400;

public static void main(String[] args) {
    SpringApplication.run(Main.class, args);
    launch(args);
}

@Override
public void start(Stage stage) throws Exception {
    var fxmlLoader = new FXMLLoader(getClass().getResource("/main.fxml"));
    Parent root = fxmlLoader.load();
    stage.setTitle("Example");
    stage.setScene(new Scene(root, APP_WIDTH, APP_HEIGHT));
    stage.show();

    Thread background = new Thread(() -> Platform.runLater(() -> {
        GlobalKeyboardHook keyboardHook = new GlobalKeyboardHook(true);

        keyboardHook.addKeyListener(new GlobalKeyAdapter() {

            @Override
            public void keyPressed(GlobalKeyEvent keyEvent) {
                System.out.println("Key pressed: " + keyEvent.getVirtualKeyCode());
            }

            @Override
            public void keyReleased(GlobalKeyEvent keyEvent) {
                System.out.println("Key released: " + keyEvent.toString());
            }
        });
    }));
    background.start();
}

Controller.java

public class Controller implements Initializable {
    @FXML
    private TextField filePath;

    private static String filePathString = "filePathString";

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        handleFilePath();
    }

    private void handleFilePath() {
        filePath.textProperty().setValue(filePathString);
        filePath.textProperty().addListener(((observable, oldValue, newValue) -> {
            filePath.commitValue();
        }));
    }
}
  • Please create a [mre] demonstrating the problem then add it to your question via an [edit]. – Slaw Jan 04 '20 at 23:42
  • Tell people which library you're using. Hint, note that this one has removeKeyListener method. https://github.com/kristian/system-hook/blob/master/src/main/java/lc/kra/system/keyboard/GlobalKeyboardHook.java – brian Jan 05 '20 at 00:53
  • I wrote a method which removes listener from hook when the text field is focused. It works but the problem still exists - I cannot edit the text. – Wojciech Pawlik Jan 05 '20 at 01:29

0 Answers0