JSpinner Value change Events

后端 未结 6 2117
梦谈多话
梦谈多话 2020-12-29 03:05

How to make the update immediately when the jSpinner value was changed.

ChangeListener listener = new ChangeListener() {
  public void stateChanged(ChangeEve         


        
6条回答
  •  长发绾君心
    2020-12-29 04:03

    It might be an late answer but you may use my approach.
    As spuas mentioned above the problem is that stateChanged event is fired only when focus is lost or Enter key is pressed.
    Using KeyListeners is not an good idea as well.
    It would be better to use DocumentListener instead. I modified spuas's example a bit and that's what I got:

    JSpinner spinner= new JSpinner();
    spinner.setModel(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 1));
    final JTextField jtf = ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField();
            jtf.getDocument().addDocumentListener(new DocumentListener() {              
    
            private volatile int value = 0;
    
            @Override
            public void removeUpdate(DocumentEvent e) {
                showChangedValue(e);    
            }
    
            @Override
            public void insertUpdate(DocumentEvent e) {
                showChangedValue(e);                
            }
    
            @Override
            public void changedUpdate(DocumentEvent e) {
                showChangedValue(e);    
            }
    
            private void showChangedValue(DocumentEvent e){
                try {
                    String text = e.getDocument().getText(0, e.getDocument().getLength());
                    if (text==null || text.isEmpty()) return;
                        int val = Integer.parseInt(text).getValue();
                    if (value!=val){
                       System.out.println(String.format("changed  value: %d",val));             
                       value = val;
                    }       
                } catch (BadLocationException | NumberFormatException e1) {
                              //handle if you want
                }        
           }
    });
    

提交回复
热议问题