【问题标题】:MouseListener and JTreeMouseListener 和 JTree
【发布时间】:2012-01-28 00:32:42
【问题描述】:

我正在使用鼠标侦听器来了解用户何时单击 JTree 的节点。虽然当用户单击箭头扩展节点(查看子节点)时,会引发以下异常:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at Core.ChannelView$1.mousePressed(ChannelView.java:120)
    at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:263)
    at java.awt.Component.processMouseEvent(Component.java:6370)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)

ChannelView 监听器:

MouseListener ml = new MouseAdapter() {

            public void mousePressed(MouseEvent e) {
                TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
                if (e.getClickCount() == 1) {
line 120>>>>>        System.out.println(selPath.getLastPathComponent());

                } else if (e.getClickCount() == 2) {
                    System.out.println("Double" +selPath.getLastPathComponent());
                }
            }
        };
        tree.addMouseListener(ml);

关于我应该如何处理这种情况的任何建议?我应该在 if 语句中简单地尝试捕获吗?这也是检查双击的好方法还是我应该用不同的方法来做?谢谢

【问题讨论】:

    标签: java swing jtree mouselistener


    【解决方案1】:

    您的侦听器尝试获取鼠标位置处的节点。如果没有任何节点,则tree.getPathForLocation() 返回 null。只需在 selPath 上调用方法之前测试它是否为 null:

    if (selPath == null) {
        System.out.println("No node at this location");
    }
    else {
        if (e.getClickCount() == 1) {
        ...
    }
    

    是的,getClickCount() 返回与事件相关的点击次数,因此检查它是双击还是简单点击似乎是合适的。

    【讨论】:

      【解决方案2】:

      我正在使用鼠标侦听器来了解用户何时单击 JTree 的节点。

      请改用TreeSelectionListenerTreeSelectionEvent 有一些非常方便的methods 用于发现哪些节点被选中/被选中。

      更多详情请见How to Use Trees - Responding to Node Selection

      【讨论】:

      • 我检查了那个监听器并实现了它,但我找不到如何检查双击。这可能吗?
      猜你喜欢
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-05
      • 2014-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多