How do I disable keyboard and mouse entry for a JSpinner?

走远了吗. 提交于 2019-12-10 13:27:48

问题


When I try to make a JSpinner un-editable by keyboard or mouse like this:

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

It disables any keyboard entry and pasting, but I can still click the up/down buttons and change the value.

How do I disable the up/down buttons?


回答1:


If the spinner uses a JSpinner.DefaultEditor or its subclass, then the following code works (keyboard navigation disabled, spinner buttons do not work, yet it is possible to select and copy the value displayed in the spinner).

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 a custom editor with something other then JTextComponent, then it is probably still possible to use the same approach (disable the spinner, re-enable the actual component used by the spinner editor, mark that component as read-only using its API).




回答2:


// 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's current value
SpinnerNumberModel snm = (SpinnerNumberModel) spinner.getModel();
snm.setMinimum((Integer)spinner.getValue());
snm.setMaximum((Integer)spinner.getValue());


来源:https://stackoverflow.com/questions/6904326/how-do-i-disable-keyboard-and-mouse-entry-for-a-jspinner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!