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).
JSpinner ActionListener alternative
Asked Answered
Your answer might be this post: https://mcmap.net/q/1326859/-java-mouseevents-not-working –
Selfdriven
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) {}
});
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
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(...);
}
}
© 2022 - 2024 — McMap. All rights reserved.