1

我正在尝试扩展 JXDatePicker 以便在获得焦点时打开它。搜索了提示我理解没有成功。有没有一种优雅的方式来做到这一点?

4

2 回答 2

3

令人惊讶的是,这实际上是不可能的:-(

这一次,JXDatePicker 本身没有 api 来显示/隐藏弹出窗口(只有 BasicDatePickerUI 有)。再加上 ui 委托有一些内部魔法(阅读:hacks ...咳),这使得 FocusListener 比通常在复合组件中更难处理。

一个片段来玩:

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);

不太令人满意,因为在再次转移焦点自动关闭弹出窗口不能可靠地工作,需要两个选项卡(不知道为什么)

于 2013-03-19T09:28:00.740 回答
0

我有同样的问题。这对我有用:

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) {}
});

这段代码用于避免焦点问题:

 e.getOppositeComponent() != getRootPane()
于 2019-02-13T14:26:38.600 回答