Daddy Warbox Daddy Warbox - 10 months ago 54
Java Question

Getting ENTER to work with a JSpinner the way it does with a JTextField

First, to make my job explaining a bit easier, here's some of my code:

JSpinner spin = new JSpinner( );
JFormattedTextField text = getTextField( spin );

text.addActionListener( new java.awt.event.ActionListener() {
public void actionPerformed( java.awt.event.ActionEvent evt ) {
// Do stuff...
} );


private JFormattedTextField getTextField( JSpinner spinner )
JComponent editor = spinner.getEditor();

if ( editor instanceof JSpinner.DefaultEditor )
return ( ( JSpinner.DefaultEditor )editor ).getTextField();
System.err.println( "Unexpected editor type: "
+ spinner.getEditor().getClass()
+ " isn't a descendant of DefaultEditor" );
return null;

So as you can see, I got that far. And indeed, when I type in a value into the text field component of the spinner (JFormattedTextField), and THEN press ENTER, it works.

What I want now is to be able to have the text field respond to ENTER without having to manually type in a new value (which sorta defeats the purpose of making a spinner out of it). How do I do that?


I know this is not the action listener...but maybe this can work for you?

    text.addKeyListener( new KeyAdapter() {
    		public void keyReleased( final KeyEvent e ) {
    			if ( e.getKeyCode() == KeyEvent.VK_ENTER ) {
    				System.out.println( "enter pressed" );
    	} );