Saturday, 10 March 2012

Java NetBeans : submit button not working when press Enter?


Today, I noticed that my form is not getting submitted while using keyboard Enter button to submit it. Then I searched over that and found different solutions and sharing them with you :

1) If your form is only having one button and that’s only submit button then use the     following line in your code:

this.getRootPane().setDefaultButton(submitButton);

I have used this line in constructor.

It would work and your submit button will be automatically get focused.

2) If you have more than one button, as in my case there are three buttons, above solution will not work. Because, on any given Window a single button can be designated as the “Default Button”. The default button is noticeable by the darker border around the button. The default button can be activated by using the Enter key, even when it doesn’t have focus. When your focus is on another button and you press enter even then only submit button is working not the one you have pressed. So in this case we have the following solution :



 
In order to make a button the default button you need to know when a button gains focus. You could add a FocusListener to every button, but this would be extremely tedius. Fortunately there is an easier way. We can add a PropertyChangeListener to the KeyboardFocusManager  and listen for focus change events. Using this approach all focus changes are handled in one place so all we need to do is manage focus changes that involve buttons. The DefaultButtonListener class will manage all this for you. You can use this class in your application with the following lines of code:

DefaultButtonListener listener = DefaultButtonListener.install();

InputMap im = (InputMap)UIManager.get("Button.focusInputMap");
im.put( KeyStroke.getKeyStroke( "ENTER" ), "pressed" );
im.put( KeyStroke.getKeyStroke( "released ENTER" ), "released" );


You can use the DefaultButtonListener class for single button as well :

InputMap im = button.getInputMap();
im.put( KeyStroke.getKeyStroke( "ENTER" ), "pressed" );
im.put( KeyStroke.getKeyStroke( "released ENTER" ), "released" );


That’s it. It worked for me. If you are facing any other similar problem and it’s not working for you please let me know.

Thanks!!!!!!!  Enjoy Programming :)


No comments:

Post a Comment

Thanks for your valuable comments.

Gmail: Download blocked file

Hi, today we are going to learn, how to download blocked file in gmail. Sometimes you see following message in gmail: and you can...