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).
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.
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.
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
}
});
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) {}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With