Opening JXDatePicker on gaining focus

1k Views Asked by At

I am trying to extend JXDatePicker so that it opens up when it gains focus. Have searched for suggest that I understand without success. Is there an elegant way of doing this?

2

There are 2 best solutions below

0
kleopatra On

Astonishingly, it's not really possible :-(

For once, the JXDatePicker itself has no api to show/hide the popup (only BasicDatePickerUI has). Plus the ui delegate has some internal magic (read: hacks ... cough) that makes a FocusListener even worse to handle than usually in compound components.

A snippet to play with:

final JXDatePicker picker = new JXDatePicker();
FocusListener l = new FocusListener() {

    @Override
    public void focusGained(FocusEvent e) {
        // no api on the picker,  need to use the ui delegate
        BasicDatePickerUI pickerUI = (BasicDatePickerUI) picker.getUI();
        if (!pickerUI.isPopupVisible()) {
            pickerUI.toggleShowPopup();
        }
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // opening the popup moves the focus to ... ? 
                // need to grab it back onto the editor
                picker.getEditor().requestFocusInWindow();
            }
        });
    }

    @Override
    public void focusLost(FocusEvent e) {
    }
};
// need to register the listener on the editor
picker.getEditor().addFocusListener(l);
JComponent content = new JPanel();
content.add(new JButton("dummy"));
content.add(picker);

Not really satisfying, as automatic closing of the popup on transfering the focus out again doesn't work reliably, needs two tabs (don't know why)

0
morlic On

I had the same problem. This worked for me:

jXDatePicker.getEditor().addFocusListener(new FocusListener() {
    @Override
    public void focusGained(FocusEvent e) {
        BasicDatePickerUI pickerUI = (BasicDatePickerUI) jXDatePicker.getUI();
        if (!pickerUI.isPopupVisible() && e.getOppositeComponent() != getRootPane() && e.getOppositeComponent() != jXDatePicker.getMonthView()) {
            pickerUI.toggleShowPopup();
        }
    }
    @Override
    public void focusLost(FocusEvent e) {}
});

This piece of code is used to avoid focus issues:

 e.getOppositeComponent() != getRootPane()