I would like to do some input validation when the ENTER key is pressed in a JDateChooser
. I know that in JTextField
elements it is possible to add an ActionListener
whereby the ENTER key fires an action. However, when I add an ActionListener
and press ENTER in the date chooser, the action is not always received.
In the below example, pressing the ENTER key when the program first starts fires an action in the JDateChooser
and the focus traverses to the next component as expected. However, in subsequent traversals, I have to enter a character before an action is fired. An action is fired in the two JTextField
elements as expected.
Can anyone explain why the ENTER key does not always behave the same when adding an ActionListener
to the editor of a JDateChooser
?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import com.toedter.calendar.JDateChooser;
public class DateExample extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DateExample frame = new DateExample();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public DateExample() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(0, 1, 0, 0));
JDateChooser dateChooser = new JDateChooser("yyyy/MM/dd", "####/##/##", '_');
((JTextField) dateChooser.getDateEditor().getUiComponent()).addActionListener(this);
contentPane.add(dateChooser);
textField = new JTextField();
textField.setColumns(10);
textField.addActionListener(this);
contentPane.add(textField);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.addActionListener(this);
contentPane.add(textField_1);
pack();
}
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Action received.");
KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
}
}