Search code examples
javaswinguser-interfacespinnerjspinner

Reseting Spinner Value in Java Swing


I have knowledge about C programming but I'm a newbie Java Programmer, and I want to ask a question to you. I try to set both spinners values null if they are less then "1" but I couldn't do it. I'm waiting for your helps, thank you.

Spinner spinnermin = new JSpinner();
    spinnermin.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent e) {
            valuemin =(Integer) spinnermin.getValue();
            if(valuemin<0){
                spinnermin.setValue(null);

            }
        }
    });
    spinnermin.setBounds(478, 215, 76, 20);
    frame.getContentPane().add(spinnermin);

    JSpinner spinnerhour = new JSpinner();
    spinnerhour.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent e) {
            valuehour = (Integer) spinnerhour.getValue();
            if(valuehour<1){
                spinnerhour.setValue(null);

            }
        }
    });
    spinnerhour.setBounds(362, 215, 86, 20);
    frame.getContentPane().add(spinnerhour);

Solution

  • You state:

    I try to set both spinners values null if they are less then "1" but I couldn't do it.

    Much better to use a SpinnerNumberModel that doesn't allow for negative values. For example,

    JSpinner hourSpinner = new JSpinner(new SpinnerNumberModel(1, 1, 24, 1));
    

    This creates a JSpinner that allows int values from 1 to 24, and that starts at 1.

    It really doesn't make sense to assign null to a component that expects to hold a numeric value, and rather than try to do this, better to limit the user's ability to input unacceptable values. Also please have a look at the JSpinner Tutorial.

    As a side recommendation, while null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.