I created this small project to test key events. But when I press keys, it isn't behaving as I want. Actually I need key events for my Calculator project. I created a Calculator project and aside from mouse clicks, I want to add a feature where numbers or operators can be typed from a keyboard. Can anyone check this and help make it more functional?
public class FXMLDocumentController implements Initializable{
@FXML
private Label label;
@FXML
private Button backSpace;
@FXML
private Button spaceBar;
@FXML
private Button enter;
@FXML
void typedBS(KeyEvent event) {
if (event.getCode() == KeyCode.BACK_SPACE) {
label.setText(event.getText() + " typed.");
}
}
@FXML
void typedE(KeyEvent event) {
if (event.getCode()==KeyCode.ENTER) {
label.setText(event.getText() + " typed");
}
}
@FXML
void typedSB(KeyEvent event) {
if (event.getCode()==KeyCode.SPACE) {
label.setText(event.getText()+" typed");
}
}
@FXML
void PressBackSpace(KeyEvent event) {
if (event.getCode() == KeyCode.BACK_SPACE) {
label.setText("You pressed Back Space key!");
}
}
@FXML
void clickBackSpace(ActionEvent event) {
label.setText("You clicked Back Space key!");
}
@FXML
void clickEnter(ActionEvent event) {
label.setText("You clicked Enter key!");
}
@FXML
void clickSpaceBar(ActionEvent event) {
label.setText("You clicked SpaceBar key!");
}
@FXML
void pressEnter(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
label.setText("You pressed Enter key!");
}
}
@FXML
void pressSpaceBar(KeyEvent event) {
if (event.getCode() == KeyCode.SPACE) {
label.setText("You pressed SpaceBar key!");
}
}
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
Define the event and the handling in the same thing. try something like this: if u are using a borderpane as an example
Hope it helps