【问题标题】:Why will JDateChooser not receive focus events为什么 JDateChooser 不会收到焦点事件
【发布时间】:2014-05-24 19:55:02
【问题描述】:

我正在尝试将 FocusAdapter 添加到 JDateChooser 摆动项目,但 focusGained() 方法没有触发,无论是通过选项卡焦点还是鼠标单击...

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

令人沮丧...我错过了什么小东西吗?

【问题讨论】:

  • 这是因为JDateChooser 没有收到焦点,它的编辑器收到了
  • @MadProgrammer,应该将其作为答案,以便我接受。
  • 必须先查一下 ;)

标签: java swing jdatechooser focuslistener


【解决方案1】:

基于JavaDocs,你需要获取作为JDateChooser的编辑器的UI组件

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

【讨论】:

  • 只是为了混淆,我之前肯定已经将FocusAdapter 直接添加到JDateChooser (我正在查看代码)并且它有效,但我无法复制功能。不知道为什么它在一个程序中有效,但在另一个程序中无效...
  • 无论哪种方式,你都是对的,这是正确的做法,即使另一种方式只是侥幸...
猜你喜欢
  • 1970-01-01
  • 2014-08-21
  • 1970-01-01
  • 1970-01-01
  • 2021-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
相关资源
最近更新 更多