How to check manual edits on a JSpinner field using DefaultEditor approach

后端 未结 4 2230
孤城傲影
孤城傲影 2021-01-24 06:07

I am adapting code from here:

Value Change Listener to JTextField

EDIT 2

The following code gives me an infinite loop of dialogs when I press the up spin

4条回答
  •  情书的邮戳
    2021-01-24 06:25

    You have a few basic choices.

    1. You could trap the exception
    2. You could check for a "empty" String

    Personally, I'd like to do both...

    public void warn() {
        String text = ((JSpinner.DefaultEditor)spin2.getEditor()).getTextField().getText();
        if (text != null && !text.trim().isEmpty()) {
            try {
                int stringValue = Integer.parseInt(text);
                JOptionPane.showMessageDialog(null,
                      "VALS: "+spin2.getValue(), "Error Massage",
                      JOptionPane.ERROR_MESSAGE);
                if (stringValue<10 || stringValue >100){
                JOptionPane.showMessageDialog(null,
                  "Error: Please enter number bigger than 0", "Error Massage",
                  JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException exp) {
                exp.printStackTrace();
            }
        }
    }
    

    Now, as a user, this is likely just to annoy me. Highlight the field, beep, change the tooltip, sure, throw a dialog in my face...hmmm...

    You could take a look at Validating Input, which will allow you to validate the input when the field loses focus, which, personally, might be a better choice.

    If you don't particularly need to functionality of the JSpinner (running values up and down in a sequence), you could take a look at using a DocumentFilter (for examples), which will allow you to control what goes into the field. You should know that it's not possible (or close enough to it) to add a DocumentFilter to a JSpinner... :P

提交回复
热议问题