1

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?

ryvantage
  • 13,064
  • 15
  • 63
  • 112

1 Answers1

3

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(...);
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Just for confusion, I've definitely added a `FocusAdapter` straight to the `JDateChooser` before (I'm looking at the code) and it worked, but I wasn't able to replicate the functionality. Not sure why it works in one program but not in another... – ryvantage Apr 10 '14 at 21:45
  • Either way, you are right and this is the proper way to do it, even if the other way worked on a fluke... – ryvantage Apr 10 '14 at 21:46