Java JSpinner fixIntegerList(final JSpinner spinner)

Here you can find the source of fixIntegerList(final JSpinner spinner)

Description

Workaround for a swing bug : when the user enters an illegal value, the text is forced to the last value.

License

Open Source License

Parameter

Parameter Description
spinner the spinner to update

Declaration

public static void fixIntegerList(final JSpinner spinner) 

Method Source Code


//package com.java2s;
// it under the terms of the GNU General Public License as published by

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JFormattedTextField;
import javax.swing.JSpinner;

import javax.swing.KeyStroke;

public class Main {
    /**/* w  w w. jav  a  2s  . co  m*/
     * Workaround for a swing bug : when the user enters an illegal value, the
     * text is forced to the last value.
     *
     * @param spinner the spinner to update
     */
    public static void fixIntegerList(final JSpinner spinner) {
        JSpinner.DefaultEditor editor;
        editor = (JSpinner.DefaultEditor) spinner.getEditor();

        final JFormattedTextField ftf = editor.getTextField();
        ftf.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enterAction");
        ftf.getActionMap().put("enterAction", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    spinner.setValue(Integer.parseInt(ftf.getText()));
                } catch (Exception ex) {
                    // Reset to last value
                    ftf.setText(ftf.getValue().toString());
                }
            }
        });
    }
}

Related

  1. createSpinner()
  2. createSpinner(SpinnerModel model)
  3. createSpinnerForm(String label, JSpinner spinner)
  4. dereferenceSpinnerNumberModel(SpinnerNumberModel model)
  5. detachChangeListeners(JSpinner spinner)
  6. formatSpinner(JSpinner spinner, String format)
  7. generateSpinnerFor(Object... objs)
  8. getFloat(JSpinner spinner)
  9. getInt(JSpinner spinner)