Java Swing How to - Disable Keyboard Editing in a JSpinner








Question

We would like to know how to disable Keyboard Editing in a JSpinner.

Answer

/*w ww . ja v  a  2s.com*/
import java.awt.Color;

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

public class Main {
  public static void main(String[] argv) throws Exception {
    JSpinner spinner = new JSpinner();

    // Disable keyboard edits in the spinner
    JFormattedTextField tf = ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField();
    tf.setEditable(false);
    tf.setBackground(Color.white);

    // The value of the spinner can still be programmatically changed
    spinner.setValue(new Integer(100));
  }
}