have tried a few different approaches to this but with no success so far. Just wondered if I'm missing anything. I have a JSpinner which is a component of a DateSelector widget alongside a Calendar. I am trying to fire a validation method if the user changes any text in the JSpinner instead of using the Calendar control or the JSpinner up and down arrows.
Here are the different approaches I have tried:
jSpinner1.addKeyListener(kl);
jSpinner1.getEditor().addKeyListener(kl);
((JSpinner.DefaultEditor) jSpinner1.getEditor().getTextField().addKeyListener(kl);
Anyone out there got any ideas as to what I'm doing wrong? Thanks
UPDATE Apologies, I should have said that I have already added a ChangeListener to the JSpinnerDateModel which is attached to the JSpinner. Like so:
ChangeListener changeListener = new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
dateChanged();
}
};
jSpinnerDateModel.addChangeListener(changeListener);
KeyListener keyListener = new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
System.out.println(e.getKeyChar());
dateChanged();
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
};
((JSpinner.DefaultEditor) jSpinner1.getEditor()).getTextField().addKeyListener(
keyListener);
Thanks
Frank
If you want to disable keyboard editing do this:
JFormattedTextField tf = ((JSpinner.DefaultEditor)spinner.getEditor()).getTextField();
tf.setEditable(false);
To listen for key events you need to add a listener to the text field. This works for me:
((JSpinner.DefaultEditor)spinner.getEditor()).getTextField().addKeyListener(new KeyListener(){
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
System.out.println("PRESSED!");
}
@Override
public void keyTyped(KeyEvent 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