Java 控制拖拽上的JTree扩展延迟&;滴

Java 控制拖拽上的JTree扩展延迟&;滴,java,swing,Java,Swing,我们的系统目前允许用户在JTree上拖放。当用户将鼠标悬停在树中的某个节点上时,我们已经编写了展开树节点的代码。然而,java和现代计算机作为节点的速度往往扩展得非常快。如果用户快速拖动树中的多个节点,则所有节点都会展开 我们需要的是在树节点扩展发生之前的一些延迟,可能是一两秒钟。使问题复杂化的是,如果用户没有在分配的延迟内停留在节点上,则节点不应展开 实现此行为的最佳方式是什么。您可以使用将在给定延迟后执行任务以扩展节点的。当用户移动到新节点上时,还可以取消挂起的任务 例: 为了获得最佳实践,

我们的系统目前允许用户在JTree上拖放。当用户将鼠标悬停在树中的某个节点上时,我们已经编写了展开树节点的代码。然而,java和现代计算机作为节点的速度往往扩展得非常快。如果用户快速拖动树中的多个节点,则所有节点都会展开

我们需要的是在树节点扩展发生之前的一些延迟,可能是一两秒钟。使问题复杂化的是,如果用户没有在分配的延迟内停留在节点上,则节点不应展开

实现此行为的最佳方式是什么。

您可以使用将在给定延迟后执行任务以扩展节点的。当用户移动到新节点上时,还可以取消挂起的任务

例:

为了获得最佳实践,您应该为“Executors.newScheduledThreadPool”提供一个线程工厂,该工厂将命名所创建的线程。有点像一辆汽车

按照斯坦尼斯拉夫的建议做实际上会更直截了当一些。每当您将鼠标悬停在某个组件上时,请计划一个将展开该组件的任务。当任务开始时,让它检查用户是否仍停留在导致任务计划的组件上

    public void hovered() {
      final Component node = node currently hovered over; // node is the component
// that is causing the task to be scheduled
      executor.schedule(new Runnable() {
        public void run() {
          // see if the node that the mouse is over now is the same node it was over 2 seconds ago
          if (getComponentUnderMouse() == node) {
            expand(node); // do this on the EDT
          } else {
            // do nothing because we are over some other node
          }
        }
      }, 2, TimeUnit.SECONDS);
    }

当鼠标移到一个节点上时,您可以以所需的延迟启动计时器。调用计时器操作时,只需检查鼠标是否仍在同一节点上。如果是,则展开它,而不是什么都不做。

我会说,它将在2秒钟后打开相同的节点。它可以在您将鼠标移出组件后打开一个节点。回答中的一些详细信息会有所帮助。mlaw的答案是使用一个调度程序和另一个线程来获取您提到的计时器行为。BenjaminLinus StanislavL的解决方案更简单一些。然后将鼠标悬停在组件上:`final component origing component=origComp;schedule(new Runnable(){public void run(){如果鼠标位于原始组件上,则展开。否则,不执行任何操作。},2,TimeUnit.SECONDS);
myRescheduler.schedule(new Runnable() {
   public void run() {
      SwingUtilities.invokeLater(task to expand the node in the tree!);
   }
}, 2, TimeUnit.SECONDS);
    public void hovered() {
      final Component node = node currently hovered over; // node is the component
// that is causing the task to be scheduled
      executor.schedule(new Runnable() {
        public void run() {
          // see if the node that the mouse is over now is the same node it was over 2 seconds ago
          if (getComponentUnderMouse() == node) {
            expand(node); // do this on the EDT
          } else {
            // do nothing because we are over some other node
          }
        }
      }, 2, TimeUnit.SECONDS);
    }