Is it possible to get a shift character in Java or JavaFX?
For example, if I have the char '1'
and I want the shift character on a qwertz layout. I get the '!'
.
Because I have a JavaFX KeyEvent
and I want the character which is pressed. But the KeyEvent
didn't get me shift character for 1
. Only for letters.
Is this possible without JNI or is there a workaround for example with a TextField
and events?
Or should I use a own Map
?
You should listen for KEY_TYPED
events and query KeyEvent#getCharacter()
. If the user types Shift+1 then #getCharacter()
will return "!"
, at least on a typical US QWERTY keyboard.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class App extends Application {
@Override
public void start(Stage primaryStage) {
Text text = new Text();
primaryStage.addEventHandler(KeyEvent.KEY_TYPED, event -> {
event.consume();
text.setText(text.getText() + event.getCharacter());
});
primaryStage.setScene(new Scene(new StackPane(text), 500, 300));
primaryStage.show();
}
}
Note: The above is not an exhaustive implementation. For instance, typing Backspace won't delete a character but will instead add an "unknown character" because the \b
character has no representation.