JTree添加鼠标事件

package org.dm.swingTest;

 

import java.awt.EventQueue;

import java.awt.event.InputEvent;

 

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JTree;import javax.swing.border.EmptyBorder;

import javax.swing.event.TreeSelectionEvent;

import javax.swing.event.TreeSelectionListener;

import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.JScrollPane;

import javax.swing.JTextField;

 

public class AppDemo extends JFrame {

 

 private JPanel contentPane;

 private JTextField textField;

 public static void main(String[] args) {

  EventQueue.invokeLater(new Runnable() {

   public void run() {

    try {

     AppDemo frame = new AppDemo();

     frame.setVisible(true);

    } catch (Exception e) {

     e.printStackTrace();

    }

   }

  });

 }

 

 public AppDemo() {

  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  setBounds(100, 100, 450, 300);

  setTitle("测试");

  contentPane = new JPanel();

  contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

  setContentPane(contentPane);

  contentPane.setLayout(null);

    JScrollPane scrollPane = new JScrollPane();

  scrollPane.setBounds(30, 20, 196, 217);

  contentPane.add(scrollPane);

    final JTree tree = new JTree();

  scrollPane.setViewportView(tree);    textField = new JTextField();

  textField.setBounds(252, 35, 172, 27);

  contentPane.add(textField);

  tree.addTreeSelectionListener(new TreeSelectionListener() {

   public void valueChanged(TreeSelectionEvent e) {

    DefaultMutableTreeNode note = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();

    String name = note.toString();//获得这个结点的名称

    textField.setText(name);

   }

  });

  //添加鼠标事件

  tree.addMouseListener(new java.awt.event.MouseAdapter() {

      public void mouseClicked(java.awt.event.MouseEvent evt) {

//        默认单击鼠标一下

//          if(evt.getClickCount()==1){

//             System.out.println("一下");

//          }

     //点击鼠标左键两下

//      1 左键

//      2 中键(Sun Mouse)

//      3 右键

          if(evt.getModifiers()==InputEvent.BUTTON1_MASK && evt.getClickCount()==2) {

              System.out.println("两下");

          }

      }

  });

 }

}

你可能感兴趣的:(JTree)