JSpinner ActionListener alternative
Asked Answered
H

3

8

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).

Houdon answered 26/4, 2013 at 19:10 Comment(1)
Your answer might be this post: https://mcmap.net/q/1326859/-java-mouseevents-not-workingSelfdriven
S
9

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
  }
});
Seagoing answered 26/4, 2013 at 19:41 Comment(0)
D
3

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) {}
});
Deadeye answered 26/4, 2013 at 19:33 Comment(2)
Like this? ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField().getDocument().addDocumentListener(new DocumentListener() {...} It doesn't seem to work...Houdon
@Creator13, yes, that is the general code. Works fine for me. Although the ChangeListener is the way to go.Deadeye
B
0

This is the only way I've found:

for (Component c : mySpinner.getComponents()) {
    if (c instanceof JButton) {
        ((JButton) c).addActionListener(...);
    }
    if (c instanceof JSpinner.DefaultEditor) {
        ((JSpinner.DefaultEditor) c).getTextField().addActionListener(...);
    }
}
Bullington answered 22/3, 2022 at 17:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.