How to check manual edits on a JSpinner field using DefaultEditor approach

后端 未结 4 2204
孤城傲影
孤城傲影 2021-01-24 06:07

I am adapting code from here:

Value Change Listener to JTextField

EDIT 2

The following code gives me an infinite loop of dialogs when I press the up spin

4条回答
  •  耶瑟儿~
    2021-01-24 06:30

    This proved to be a huge pain the rear. I wanted to color my text field background immediately. Ended up making an editor that overrode the editor I wanted to use, then setting it as the spinners editor accordingly. Seems to be working for me so far.

    Add a java class with the following (remove the quotes around the code block, I'm having a hard time with stack overflow's editor):

    `public class CustomNumberEditor extends JSpinner.NumberEditor {
        public CustomNumberEditor( JSpinner spinner ) {
            super( spinner );
            ((DefaultFormatter ) ((JFormattedTextField) getComponent( 0 )).getFormatter()).setCommitsOnValidEdit( true );
        }
        @Override public void propertyChange(PropertyChangeEvent e) {
            super.propertyChange( e );
            if( e.getPropertyName().equals( "value" ) )
                doStuff( (int) e.getNewValue() );
        }
        private void doStuff( int value )
        {
            //do stuff
        }
    }`
    

    Then when adding your spinner, do this:

    _quantitySpinner.setEditor(new CustomNumberEditor(_quantitySpinner));
    

提交回复
热议问题