JDateChooser:鼠标点击事件不会被触发



我想双击JDateChooser使其启用。所以我使用mousellistener:

jDateChooser1.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            System.out.println("mouse clicked");
        }
    });

但是这个事件没有被触发,什么也没有发生。

日期选择器是com.toedter.calendar:

有什么建议吗?

解决方案

JDateChooser是一个面板,我必须监听来自面板中某个组件的鼠标事件。JDateChooser有一个getDateEditor(),它是文本字段。

解决方案如下:

this.jDateChooser1.getDateEditor().getUiComponent().addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if(evt.getClickCount()==2){               
                Component c = ((Component)evt.getSource()).getParent();
                c.setEnabled(!c.isEnabled());
            }
        }
    });

JDateChooser类扩展了JPanel。我猜您正在单击的区域是在添加到根JPanel的另一个容器中找到的。您应该尝试识别哪个容器是触发事件的容器,并向其添加侦听器。

来测试这是否正确,尝试递归地将侦听器添加到所有容器中,如果看到它被触发,则可以删除侦听器的递归设置,并尝试确定需要将mousellistener添加到哪个容器中。(注意我直接写代码没有测试,所以请修复任何错误)

private void addMouseListenerRecrusively(Container container){
   for (Component component:container.getComponents()){
     if (component instanceof Container)
        addMouseListenerRecrusively(component); 
   }
   container.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            System.out.println("mouse clicked");
        }
    });
}

并调用选择器

上的方法
addMouseListenerRecrusively(jDateChooser1);

最新更新