Jan Zähnler
Jan Zähnler

Reputation: 11

How can I disable the spacebar in a textfield in JavaFX?

I got a question. I would like to disable the space bar completely for that textfield so there are no spaces in my input. How is that possible?

if (event.getCode() == KeyCode.SPACE) {
                    System.out.println("Spacebar key detected!");
                    textfieldName.setText(textfieldName.getText().substring(textfieldName.getLength() -1));
                }
            });

This is what I found, but I would like to disable the spacebar completely. Can anyone help me please?

Thanks for answering :)

Upvotes: 1

Views: 513

Answers (1)

Lidor shimoni
Lidor shimoni

Reputation: 93

Maybe this will help

mytextfield.addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
        public void handle(KeyEvent event) {          
            if (event.getCode() == KeyCode.SPACE) {
                event.consume(); // to cancel space key               
            }
        }
    });

Another way is to filter it like @n247s suggested in the comments

Upvotes: 1

Related Questions