Fire Button's onAction with Enter in JavaFX

前端 未结 3 1898
生来不讨喜
生来不讨喜 2020-12-10 13:58

I\'m a newbie to JavaFx. In my JavaFX application I have set onAction property and it works fine when I press the button using mouse. I want to fire the same even when user

3条回答
  •  萌比男神i
    2020-12-10 14:21

    If you want to apply this to every Button in your program you can subclass the JavaFX-Button and bind this in the constructor. In your fxml-File you'll need to include your custom Button.

    I wrote the following subclass:

    public class FocusedButton extends javafx.scene.control.Button {
    
        public FocusedButton ( ) {
            super ( );
            bindFocusToDefault ( );
        }
    
        public FocusedButton ( String text ) {
            super ( text );
            bindFocusToDefault ( );
        }
    
        public FocusedButton ( String text, Node graphic ) {
            super ( text, graphic );
            bindFocusToDefault ( );
        }
    
        private void bindFocusToDefault ( ) {
            defaultButtonProperty().bind(focusedProperty());
        }
    
    }
    

    To use this Code you will need to include your custom class in the fxml-File:

    
    

    If you want to use the Scene Builder things get a little bit more difficult: You'll need to export your custom Button in a jar-file and add this to Scene Builder as described here

提交回复
热议问题