打开JXDatePicker以获得焦点

问题描述 投票:1回答:2

我正在尝试扩展JXDatePicker,以便在获得焦点时打开它。已搜索过我没有成功理解的建议。这样做有一种优雅的方式吗?

java swing datepicker swingx jpopup
2个回答
3
投票

令人惊讶的是,它真的不可能:-(

一次,JXDatePicker本身没有api来显示/隐藏弹出窗口(只有BasicDatePickerUI有)。另外,ui委托有一些内部魔法(阅读:黑客......咳嗽),这使得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);

不太满意,因为再次将焦点转移出来时自动关闭弹出窗口不能可靠地工作,需要两个标签(不知道为什么)


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()
© www.soinside.com 2019 - 2024. All rights reserved.