ManInMoon
ManInMoon

Reputation: 7005

How can I inform a user that the value he's entered has been constrained to the JSpinner lower bound?

I need to display an error message and NOT change value of a spinner if user types a value outside of the bounds.

If the spinner buttons are used there is no issue. But if user types a number lower than lower bound, the spinner automatically sets it to the lower bound value. Which may be good BUT I need to make sure user is aware.

SpinnerNumberModel spin = new SpinnerNumberModel(10, 10, 100, 5);
mySpin = new JSpinner();
mySpin.setModel(spin);

If user types in 3 the spinner will get set to 10. But I need to confirm with user that this is what he wants.

EDIT 1

I coded up TIM B's suggestion.

I get the JOptionPane when I change value with spinner buttons. But it does not get triggered if I edit the field manually.

    import javax.swing.JOptionPane;
    import javax.swing.SpinnerNumberModel;

    public class MySpinnerNumberModel extends SpinnerNumberModel{
    public MySpinnerNumberModel(int def, int start, int end, int increment){
        this.setValue(def);
        this.setMinimum(start);
        this.setMaximum(end);
        this.setStepSize(increment);
    }

    public void setValue(Object value) {
        JOptionPane.showMessageDialog(null,"VALUE: "+value);
      super.setValue(value);
      if (value instanceof Integer) {
         int v = (Integer)value;
         //JOptionPane.showMessageDialog(null,"VALUE: "+v);
         // Check v here and act as appropriate
      }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub    
    }    
}

Upvotes: 0

Views: 276

Answers (1)

Tim B
Tim B

Reputation: 41188

You can provide your own implementation of the class enforcing the bounds and show your popup from that. I can't think of any way to do it off hand from the standard classes but implementing your own model is pretty trivial.

JSpinner:

http://docs.oracle.com/javase/7/docs/api/javax/swing/JSpinner.html

Underneath it has a SpinnerModel:

http://docs.oracle.com/javase/7/docs/api/javax/swing/SpinnerModel.html

You are probably using a SpinnerNumberModel:

http://docs.oracle.com/javase/7/docs/api/javax/swing/SpinnerNumberModel.html

Rather than using the default one create your own sub class and over-ride the setValue method:

http://docs.oracle.com/javase/7/docs/api/javax/swing/SpinnerNumberModel.html#setValue%28java.lang.Object%29

To call super.setValue() and then if the value was too low display the warning message.

class MySpinnerNumberModel extends SpinnerNumberModel {
   // You will need to implement the constructors too

   public void setValue(Object value) {
      super.setValue(value);
      if (value instanceof Integer) {
         int v = (Integer)value;
         // Check v here and act as appropriate
      }
   }
}

Upvotes: 2

Related Questions