两个JTree之间的单向拖拽

类别:Java 点击:0 评论:0 推荐:

最近因为在一个项目中要实现JTree之间的拖拽,刚刚学习开始学习Java,参照网上的代码完成的,现在贴出来共享,希望对和我一样的菜鸟有点帮助,有什么错误的话还请多多指正。

DragSourceTree.java

package aabbcc;

import javax.swing.JTree;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragSource;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.datatransfer.StringSelection;

/**
 * <p>Title: JTree之间的拖拽中的DragSourceTree</p>
 * <p>Description:通过向从“源树”中拖拽结点在目标树中重新构造一棵树,实现JTree之间的拖拽单向拖拽,这个类是“源树”。 </p>
 * @author awaysrain(绝对零度)
 * @version 1.0
 */

public class DragSourceTree
    extends JTree
    implements DragGestureListener, DragSourceListener {
  private DragSource dragSource = null;
  /**
   * Construct the source tree
   */
  public DragSourceTree() {
    super();
    dragSource = DragSource.getDefaultDragSource();
    dragSource.createDefaultDragGestureRecognizer(this,
                                                  java.awt.dnd.DnDConstants.
                                                  ACTION_COPY_OR_MOVE, this);
  }
  /**
   * Construct the source tree
   * @param treeNode DefaultMutableTreeNode
   */
  public DragSourceTree(DefaultMutableTreeNode treeNode) {
    super(treeNode);
    dragSource = DragSource.getDefaultDragSource();
    dragSource.createDefaultDragGestureRecognizer(this,
                                                  java.awt.dnd.DnDConstants.
                                                  ACTION_COPY_OR_MOVE, this);
  }

  /**
   * dragGestureRecognized
   *
   * @param dge DragGestureEvent
   */
  public void dragGestureRecognized(DragGestureEvent dge) {
    java.awt.Cursor cursor = null;
    cursor = DragSource.DefaultCopyDrop; //set cursor
    java.awt.Point jap = dge.getDragOrigin(); //drag point
    int x = (int) jap.getX();
    int y = (int) jap.getY();
    javax.swing.tree.TreePath tp = this.getPathForLocation(x, y); //get drag node path
    if (tp != null) {
      DefaultMutableTreeNode node1 = (DefaultMutableTreeNode)
          tp.getLastPathComponent(); //get drag node
      serializableNode(node1); //Serializable node object
    }
    //event start   
    dge.startDrag(cursor, new StringSelection("drag"), this);

  }

  /**
   * dragEnter
   *
   * @param dsde DragSourceDragEvent
   */
  public void dragEnter(DragSourceDragEvent dsde) {
  }

  /**
   * dragOver
   *
   * @param dsde DragSourceDragEvent
   */
  public void dragOver(DragSourceDragEvent dsde) {
  }

  /**
   * dropActionChanged
   *
   * @param dsde DragSourceDragEvent
   */
  public void dropActionChanged(DragSourceDragEvent dsde) {
  }

  /**
   * dragDropEnd
   *
   * @param dsde DragSourceDropEvent
   */
  public void dragDropEnd(DragSourceDropEvent dsde) {
  }

  /**
   * dragExit
   *
   * @param dse DragSourceEvent
   */
  public void dragExit(DragSourceEvent dse) {
  }
  /**
   *Serializable node 
   *
   * @param node DefaultMutableTreeNode
   */
  private void serializableNode(DefaultMutableTreeNode node) {
    try {
      java.io.FileOutputStream objfile = new java.io.FileOutputStream(
          "DragNode.OBJ");
      java.io.ObjectOutputStream p = new java.io.ObjectOutputStream(objfile);
      p.writeObject(node);
      p.flush();
      objfile.close();
    }
    catch (java.io.IOException e) {
      System.out.println(e.toString());
    }

  }
}

DragTargetTree.java
package aabbcc;

import javax.swing.JTree;
import java.awt.dnd.DropTargetListener;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTarget;
import java.io.*;
import java.io.*;
import javax.swing.tree.DefaultMutableTreeNode;

/**
 * <p>Title: JTree之间的拖拽中的DragTargetTree</p>
 * <p>Description:通过向从“源树”中拖拽结点在目标树中重新构造一棵树,实现JTree之间的拖拽单向拖拽,这个类是“目的树” </p>
 * @author awaysrain(绝对零度)
 * @version 1.0
 */

public class DragTargetTree
    extends JTree
    implements DropTargetListener {
  /**
   * Construct the target tree
   */
  public DragTargetTree() {
    super();
    DropTarget dropTarget = new DropTarget(this,
                                           java.awt.dnd.DnDConstants.
                                           ACTION_COPY_OR_MOVE, this);
  }
  /**
   *  Construct the target tree
   * @param treeNode DefaultMutableTreeNode
   */
  public DragTargetTree(DefaultMutableTreeNode treeNode) {
    super(treeNode);
    DropTarget dropTarget = new DropTarget(this,
                                           java.awt.dnd.DnDConstants.
                                           ACTION_COPY_OR_MOVE, this);
  }


  /**  
   * dragEnter
   *
   * @param dtde DropTargetDragEvent
   */
  public void dragEnter(DropTargetDragEvent dtde) {
  }

  /**
   * dragOver
   *
   * @param dtde DropTargetDragEvent
   */
  public void dragOver(DropTargetDragEvent dtde) {
  }

  /**
   * dropActionChanged
   *
   * @param dtde DropTargetDragEvent
   */
  public void dropActionChanged(DropTargetDragEvent dtde) {
  }

  /**
   * drop
   *
   * @param dtde DropTargetDropEvent
   */
  public void drop(DropTargetDropEvent dtde) {
    dtde.acceptDrop(java.awt.dnd.DnDConstants.ACTION_COPY); //accept drop
    java.awt.Point ap = dtde.getLocation(); // get event point
    int x = (int) ap.getX();
    int y = (int) ap.getY();
    javax.swing.tree.DefaultMutableTreeNode parnode;
    javax.swing.tree.TreePath tp = this.getPathForLocation(x, y);
    if (tp != null) {
        try {
        //get drop tree node with treepath
        javax.swing.tree.DefaultMutableTreeNode no1 =
            (javax.swing.tree.DefaultMutableTreeNode) tp.getLastPathComponent();
        parnode = no1;
        int index = parnode.getChildCount();
        // get drop tree mode
        javax.swing.tree.DefaultTreeModel tm =
            (javax.swing.tree.DefaultTreeModel)this.getModel();
        javax.swing.tree.DefaultMutableTreeNode node2 =
            new javax.swing.tree.DefaultMutableTreeNode();
        node2 = readNode();
        tm.insertNodeInto(node2, parnode, index);
      }
      catch (java.lang.Exception e) {
        System.out.println(e.toString());
      }
    }

  }

  /**
   * dragExit
   *
   * @param dte DropTargetEvent
   */
  public void dragExit(DropTargetEvent dte) {
  }

  /**
   *
   * read the node
   * @return DefaultMutableTreeNode
   */ 
  private DefaultMutableTreeNode readNode() {

    FileInputStream objfile = null;
    try {
      objfile = new java.io.FileInputStream("DragNode.OBJ");
      ObjectInputStream q = new ObjectInputStream(objfile);
      DefaultMutableTreeNode node = (DefaultMutableTreeNode) q.readObject();
      return node;
    }
    catch (Exception ex) {
      return null;
    }
  }
}

Demo.java

package aabbcc;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import com.borland.jbcl.layout.*;

/**
 * <p>Title: JTree之间的拖拽测试</p>
 * <p>Description:通过向从“源树”中拖拽结点在目标树中重新构造一棵树,实现JTree之间的拖拽单向拖拽,这个类测试的类 </p>
 * @author awaysrain(绝对零度)
 */


public class Demo extends JFrame {
  JPanel contentPane;
  JScrollPane jScrollPane1 = new JScrollPane();
  XYLayout xYLayout1 = new XYLayout();
  DragSourceTree jTree1 = new DragSourceTree();
  JScrollPane jScrollPane2 = new JScrollPane();
  DragTargetTree jTree2 = new DragTargetTree();
  JLabel jLabel1 = new JLabel();
  JLabel jLabel2 = new JLabel();

  //Construct the frame
  public Demo () {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
      jbInit();
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }

  //Component initialization
  private void jbInit() throws Exception  {
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(xYLayout1);
    this.setSize(new Dimension(400, 300));
    this.setTitle("Demo");
    jLabel1.setFont(new java.awt.Font("DialogInput", 0, 16));
    jLabel1.setText("源树");
    jLabel2.setEnabled(true);
    jLabel2.setFont(new java.awt.Font("DialogInput", 0, 16));
    jLabel2.setDebugGraphicsOptions(0);
    jLabel2.setDoubleBuffered(false);
    jLabel2.setVerifyInputWhenFocusTarget(true);
    jLabel2.setDisplayedMnemonic('0');
    jLabel2.setText("目标树");
    jLabel2.setVerticalAlignment(javax.swing.SwingConstants.CENTER);
    jLabel2.setVerticalTextPosition(javax.swing.SwingConstants.CENTER);
    contentPane.add(jLabel1,  new XYConstraints(35, 8, 139, 27));
    contentPane.add(jLabel2,    new XYConstraints(214, 10, 149, 20));
    contentPane.add(jScrollPane2, new XYConstraints(211, 31, 159, 231));
    contentPane.add(jScrollPane1, new XYConstraints(25, 31, 153, 230));
    jScrollPane1.getViewport().add(jTree1, null);
    jScrollPane2.getViewport().add(jTree2, null);
  }

  //Overridden so we can exit when window is closed
  protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
      System.exit(0);
    }
  }
}

本文地址:http://com.8s8s.com/it/it16739.htm