Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSpinner ActionListener alternative

In my program, I want to use a JSpinner for a number. This number will later be used to calculate something. Every time the user clicks one of the spinner buttons (up or down), I want the result to update automatically. Since you can't add an ActionListener to a JSpinner (which I think is really weird), I am asking here how to do something similar to this (I already have an ActionListener ready for this, which can be changed in any other listener of course).

like image 531
cvbattum Avatar asked Apr 26 '13 19:04

cvbattum


People also ask

What is JSpinner in Java?

A JSpinner has a single child component that's responsible for displaying and potentially changing the current element or value of the model, which is called the editor . The editor is created by the JSpinner 's constructor and can be changed with the editor property.

What are the different uses of spinner in Netbeans?

Spinners are similar to combo boxes and lists in that they let the user choose from a range of values. Like editable combo boxes, spinners allow the user to type in a value. Unlike combo boxes, spinners do not have a drop-down list that can cover up other components.


2 Answers

You could add a ChangeListener to the spinner. This will be triggered by the button presses (or a direct edit of the field).

spinner.addChangeListener(new ChangeListener() {      
  @Override
  public void stateChanged(ChangeEvent e) {
    // handle click
  }
});
like image 132
Duncan Jones Avatar answered Sep 19 '22 22:09

Duncan Jones


Every time the user clicks one of the spinner button (up or down), I want the result to update automatically.

Add a DocumentListener to the Document of the text field that is being used as the editor of the spinner.

Edit:

JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor)number.getEditor();
JTextField textField = editor.getTextField();
textField.getDocument().addDocumentListener( new DocumentListener()
{
    public void insertUpdate(DocumentEvent e)
    {
        System.out.println("insert");
    }

    public void removeUpdate(DocumentEvent e)
    {
        System.out.println("remove");
    }

    public void changedUpdate(DocumentEvent e) {}
});
like image 26
camickr Avatar answered Sep 20 '22 22:09

camickr