Search code examples
javaswinguser-interfacejspinner

Detect when max limit is reached on JSpinner?


I currently have a JSpinner implemented into my form which holds the amount of time taken to do a task; the current limit of this spinner is 180 minutes. My question is how would I detect that the spinner is currently at it's max value so that when the user tries to press the button to increment the amount of minutes I can output a message that notifies them that the max amount of time to perform a task is 180 minutes?


Solution

  • Once a JSpinner has reached the limit value, you don't get any more change events from it.

    Create a subclass of javax.swing.SpinnerNumberModel that has a custom "setValue(..)" method that notifies your code when the UI attempts to set a value that's too large. Then install it in your JSpinner object with

    mySpinner.setModel(new MySpinnerModel())
    

    But a larger question is whether you should be doing this at all. A JSpinner has a well-understood UI; people are (meant to be) used to how it performs. Getting a dialog box that you'll have to dismiss or some other unexpected behavior might not make them happy.