1

我知道我可以将 mouseListener 添加到 Jtree,但我需要双击他的一个元素并 doSomething();

4

2 回答 2

5

JTree 的文档中

如果您有兴趣检测双击事件或用户单击节点时,无论它是否被选中,我们建议您执行以下操作:

final JTree tree = ...;

 MouseListener ml = new MouseAdapter() {
     public void mousePressed(MouseEvent e) {
         int selRow = tree.getRowForLocation(e.getX(), e.getY());
         TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
         if(selRow != -1) {
             if(e.getClickCount() == 1) {
                 mySingleClick(selRow, selPath);
             }
             else if(e.getClickCount() == 2) {
                 myDoubleClick(selRow, selPath);
             }
         }
     }
 };
 tree.addMouseListener(ml);
于 2012-10-11T18:57:31.697 回答
1

检查这个: -

  public class NetworkTree extends JPanel implements TreeSelectionListener {
  private JTree tree;
  private static int PANEL_WIDTH=250;
  private static int PANEL_HEIGHT=500;
private static String lineStyle = "Horizontal";

public NetworkTree() {
DefaultMutableTreeNode top = new DefaultMutableTreeNode(new Site(
                1,1,"Network","",3));
getSubNodes(top,0);
tree = new JTree(top);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addTreeSelectionListener(this);
JScrollPane treeView = new JScrollPane(tree);
add(treeView);

tree.addMouseListener(new MouseAdapter() {
  public void mouseClicked(MouseEvent me) {
    newNodeSelected();
  }
});
 }
.....
    public void newNodeSelected() {
   JOptionPane.showMessageDialog(null,"Hello");
}

..... }

于 2012-10-11T18:55:46.130 回答