javaswingjdatechooserfocuslistener

Why will JDateChooser not receive focus events


I am trying to add a FocusAdapter to a JDateChooser swing item, but the focusGained() method is not firing, neither through a tab focus or a mouse-click...

public static void main(String[] args) {
    JPanel panel = new JPanel(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 1;

    JTextField textField = new JTextField();
    panel.add(textField, c);
    JDateChooser dateChooser = new JDateChooser(new Date());
    dateChooser.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent evt) {
            System.out.println(evt.getSource()); // This line never runs
        }
    });

    c.gridy = 1;
    panel.add(dateChooser, c);

    JFrame frame = new JFrame();
    frame.add(panel);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

Frustrating... Am I missing something small?


Solution

  • Based on the JavaDocs, you need to get the UI component that is acting as the editor for the JDateChooser

    JDateChooser dateChooser = new JDateChooser(new Date());
    IDateEditor editor = dateChooser.getDateEditor();
    JComponent comp = editor.getUiComponent();
    comp.addFocusListener(...);