[英]Java: How to disable JSpinner beeping
When invalid input is entered into the JSpinner, a beep is played, and I can't figure out how to disable it. 当无效输入输入JSpinner时,会发出一声嘟嘟声,我无法弄清楚如何禁用它。
I'm using a number spinner with invalid input not being allowed to be typed in, like so: 我正在使用一个带有无效输入的数字微调器,不允许输入,如下所示:
public class SpinnerTester {
public static void main(String[] args) {
JSpinner spinner = new JSpinner(new SpinnerNumberModel(1, 0, 100, 1));
//disable invalid input from being typed into spinner
JFormattedTextField textField = ((JSpinner.NumberEditor) spinner.getEditor()).getTextField();
((NumberFormatter) textField.getFormatter()).setAllowsInvalid(false);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(spinner);
frame.setVisible(true);
frame.pack();
}
}
I do not know if there is a better way, but one way is to make a custom look and feel that disables beeping altogether. 我不知道是否有更好的方法,但一种方法是制作一个自定义的外观和感觉,完全禁用哔哔声。 This achieves the desired effect, but also disables beeping for the entire program, not just the spinner.
这样可以达到预期的效果,但也可以禁用整个程序的蜂鸣声,而不仅仅是微调器。
public class SpinnerTester {
public static void main(String[] args) {
JSpinner spinner = new JSpinner(new SpinnerNumberModel(1, 0, 100, 1));
//disable invalid input from being typed into spinner
JFormattedTextField textField = ((JSpinner.NumberEditor) spinner.getEditor()).getTextField();
((NumberFormatter) textField.getFormatter()).setAllowsInvalid(false);
/**
* Change look and field
*/
try {
UIManager.setLookAndFeel(new MyLookAndFeel());
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(spinner);
frame.setVisible(true);
frame.pack();
}
/**
* Create Look and Feel without beeps
*/
public static class MyLookAndFeel extends NimbusLookAndFeel {
@Override
public void provideErrorFeedback(Component component) {
//super.provideErrorFeedback(component);
}
}
}
Based off an answer to this question . 基于这个问题的答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.