Search code examples
javainputjspinnerbeep

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.

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();
    }

}

Solution

  • 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.