有没有办法检测是否即将发生掉落在JTree上?

时间:2011-05-24 09:06:20

标签: java swing drag-and-drop jtree

我有一个JTree,用户可以从其他组件中删除元素。当用户将鼠标悬停在树中的节点上时(在“丢弃模式”期间),突出显示最接近的节点。这是在TransferHandler的实现中实现的。

@Override
public boolean canImport(TransferSupport support) {

    //Highlight the most near lying node in the tree as the user drags the 
    //mouse over nodes in the tree.
    support.setShowDropLocation(true);

每次选择一个新节点时(也在“丢弃模式”期间),这将启动一个TreeSelectionEvent。这反过来将调用我创建的侦听器,该侦听器将查询数据库以获取与该节点相关的详细信息。

现在,我正在寻找一种方法来以某种方式过滤掉“丢弃模式”期间从节点选择中生成的事件。这是一种限制数据库调用的尝试。有没有人对我如何实现这一点有任何想法?

所有输入都将受到高度赞赏!

1 个答案:

答案 0 :(得分:1)

有一种非常间接的方法来检测这种情况。您可以在属性PropertyChangeListener上使用树组件注册"dropLocation"。只要放置位置发生变化,就会调用此方法,因此您可以在其中设置一个字段dropOn,然后您可以在TreeSelectionListener中读取该字段。

tree.addPropertyChangeListener("dropLocation", new PropertyChangeListener() {
    public void propertyChange(PropertyChangeEvent pce) {
        dropOn = pce.getNewValue() != null;
    }
});

tree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
    public void valueChanged(TreeSelectionEvent tse) {
        System.out.println(tse + " dropOn=" + dropOn);
    }
});

请注意,这会在第一次进入树时触发错误的false值,但所有后续事件都会显示dropOn = true