我想在按 ENTER 键时进行一些输入验证JDateChooser
。我知道在JTextField
元素中可以添加一个ActionListener
ENTER 键触发一个动作。但是,当我ActionListener
在日期选择器中添加并按 ENTER 时,并不总是会收到该操作。
在下面的示例中,当程序第一次启动时按 ENTER 键会在 中触发一个动作,JDateChooser
并且焦点会按预期遍历到下一个组件。但是,在随后的遍历中,我必须在触发动作之前输入一个字符。JTextField
正如预期的那样,在这两个元素中触发了一个动作。
谁能解释为什么在将 a 添加ActionListener
到 a 的编辑器时 ENTER 键的行为并不总是相同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();
}
}