How to disable keyboard and mouse input for JSpinner?

When I try to make JSpinner inaccessible for editing with the keyboard or mouse, for example:

((DefaultEditor) mySpinner.getEditor()).getTextField().setEditable(false); mySpinner.setEnabled(false); 

It disables keyboard input and insertion, but I can still press the up / down buttons and change the value.

How to disable the up / down buttons?

+6
source share
2 answers

If the spinner uses JSpinner.DefaultEditor or its subclass, the following code works (the keyboard is disabled, the counter buttons do not work, but you can select and copy the value displayed on the counter).

 JSpinner component = ...; component.setEnabled( false ); if ( component.getEditor() instanceof JSpinner.DefaultEditor ) { JSpinner.DefaultEditor editor = ( JSpinner.DefaultEditor ) component.getEditor(); editor.getTextField().setEnabled( true ); editor.getTextField().setEditable( false ); } 

If the spinner has its own editor with something other than JTextComponent, then you can probably still use the same approach (disable the counter, re-enable the actual component used by the spinner editor, mark this component read as using only the API).

+1
source
 // Disabling mouse input without desabling the JSpinner itself JSpinner spinner = ...; // set the minimum and maximum values to the current value, // thus preventing changes to the spinner current value SpinnerNumberModel snm = (SpinnerNumberModel) spinner.getModel(); snm.setMinimum((Integer)spinner.getValue()); snm.setMaximum((Integer)spinner.getValue()); 
-1
source

Source: https://habr.com/ru/post/894062/


All Articles