• JAVA拖拽



    sun在java2中引入了一些新的方法来帮助实现拖拽功能,这些新的类在java.awt.dnd包中
    实现一个D&D操作一般包括三个步骤:
     首先实现一个拖拽源,这个拖拽源和相应的组件是关联起来的
     第二步实现一个拖拽目标,这个目标用来实现拖拽物的接收
     第三步实现一个数据传输对象,该对象封装拖动的数据
      _____________________                                      _____________________
     |                     |                                     |                    |   
     | DragSource Component|                                     |DropTarget Component|
     |_____________________|                                     |____________________|
                       |                                              |
                       |____________Transferable Data_________________|
                       
     Transferable 接口实现出的对象能够保证  DropTarget Component读懂拖拽过来的对象中包含的信息
     如果是在同一个虚拟机中实现拖拽的话,DragSource Component会传递一个引用给DropTarget Component
     但是如果在不同的JVM中或者是在JVM和本地系统之间传递数据的话我们就必须实现一个Transferable对象来传递数据
     Transferable中封装的内容存放到DataFlavors,用户可以通过访问DataFlavors来获取数据
     1。创建可拖拽对象
       一个对象那个如果想作为拖拽源的话,必须和五个对象建立联系,这五个对象分别是:
        * java.awt.dnd.DragSource
        获取DragSource的方法很简单,直接调用DragSource.getDefaultDragSource();就可以得到DragSource对象
        * java.awt.dnd.DragGestureRecognizer
        DragGestureRecognizer类中实现了一些与平台无关的方法,我们如果想在自己的组件上实现拖拽的话只要调用createDefaultDragGestureRecognizer()方法就可以了
        该方法接收三个参数,建立组件和拖拽动作之间的关系
        * java.awt.dnd.DragGestureListener
        当建立了组件和拖拽动作之间的联系后,如果用户执行了拖拽操作,组件将发送一个消息给DragGestureListener监听器
        DragGestureListener监听器接下来会发送一个startDrag()消息给拖拽源对象,告诉组件应该执行拖拽的初始化操作了
        拖拽源会产生一个DragSourceContext对象来监听动作的状态,这个监听过程是通过监听本地方法DragSourceContextPeer来实现的
        * java.awt.datatransfer.Transferable
        * java.awt.dnd.DragSourceListener 
        DragSourceListener接口负责当鼠标拖拽对象经过组件时的可视化处理, DragSourceListener接口的显示结果只是暂时改变组件的外观
        同时他提供一个feedback,当用户的拖拽操作完成之后会收到一个dragDropEnd的消息,我们可以在这个函数中执行相应的操作
        再来回顾一下拖拽源的建立过程
        首先、 DragGestureRecognizer 确认一个拖拽操作,同时告知 DragGestureListener.
        其次、 Assuming the actions and/or flavors are OK, DragGestureListener asks DragSource to startDrag().
        第三、 DragSource creates a DragSourceContext and a DragSourceContextPeer. The DragSourceContext adds itself as a DragSourceListener to the DragSourceContextPeer.
        第四、 DragSourceContextPeer receives state notifications (component entered/exited/is over) from the native system and delegates them to the DragSourceContext.
        第五、 The DragSourceContext notifies the DragSourceListener, which provides drag over feedback (if the DropTargetListener accepts the action). Typical feedback includes asking the DragSourceContext to change the cursor.
        最后、 When the drop is complete, the DragSourceListener receives a dragDropEnd notification message

    2。创建droppable Component
       创建一个 droppable Component必须和下面两个对象发生关联   
        * java.awt.dnd.DropTarget
        DropTarget构造函数使DropTarget 和 DropTargetListener objects发生关联
        Droptarget对象提供 setComponent 和addDropTargetListener 两个方法
        * java.awt.dnd.DropTargetListener 
        The DropTargetListener needs an association with the Component so that the Component can notify the DropTargetListener to display "drag under" effects during the operation. This listener, which can be conveniently created as an inner class, transfers the data when the drop occurs. Warning: The Component itself shouldn't be the listener, since this implies its availability for use as some other Component's listener.

      1 public class DragAndDrop extends JFrame {
      2     private static final long serialVersionUID = 1L;
      3     JScrollPane jScrollPane1 = new JScrollPane();
      4     JTextField jtf = new JTextField();
      5 
      6     public DragAndDrop() {
      7         getContentPane().setLayout(new BorderLayout());
      8         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      9         jtf.setBackground(Color.yellow);
     10         jtf.setSize(100, 80);
     11         JPanel panel1 = new JPanel(new BorderLayout());
     12         panel1.add(jtf, BorderLayout.CENTER);
     13         JTree jtr = new JTree();
     14         jScrollPane1.getViewport().add(jtr);
     15         add(panel1, BorderLayout.SOUTH);
     16         add(jScrollPane1, BorderLayout.CENTER);
     17 
     18         DragSource dragSource = DragSource.getDefaultDragSource(); // 创建拖拽源
     19         dragSource.createDefaultDragGestureRecognizer(jtr,
     20                 DnDConstants.ACTION_COPY_OR_MOVE, new MyDragGestureListener()); // 建立拖拽源和事件的联系
     21         new DropTarget(jtf, new MyTargetListener());
     22 
     23     }
     24 
     25     public static void main(String[] args) {
     26         DragAndDrop dad = new DragAndDrop();
     27         dad.setTitle("拖拽演示");
     28         dad.setSize(400, 300);
     29         dad.setVisible(true);
     30 
     31     }
     32 }
     33 
     34 class MyDragGestureListener implements DragGestureListener {
     35     public void dragGestureRecognized(DragGestureEvent dge) {
     36         // 将数据存储到Transferable中,然后通知组件开始调用startDrag()初始化
     37         JTree tree = (JTree) dge.getComponent();
     38         TreePath path = tree.getSelectionPath();
     39         if (path != null) {
     40             DefaultMutableTreeNode selection = (DefaultMutableTreeNode) path
     41                     .getLastPathComponent();
     42             MyTransferable dragAndDropTransferable = new MyTransferable(
     43                     selection);
     44             dge.startDrag(DragSource.DefaultCopyDrop, dragAndDropTransferable,
     45                     new MySourceListener());
     46         }
     47     }
     48 
     49 }
     50 
     51 class MyTransferable implements Transferable {
     52     private DefaultMutableTreeNode treeNode;
     53 
     54     MyTransferable(DefaultMutableTreeNode treeNode) {
     55         this.treeNode = treeNode;
     56     }
     57 
     58     static DataFlavor flavors[] = { DataFlavor.stringFlavor };
     59 
     60     public DataFlavor[] getTransferDataFlavors() {
     61         return flavors;
     62     }
     63 
     64     public boolean isDataFlavorSupported(DataFlavor flavor) {
     65         // if (treeNode.getChildCount() == 0) {
     66         // return true;
     67         // }
     68         return true;
     69     }
     70 
     71     public Object getTransferData(DataFlavor flavor)
     72             throws UnsupportedFlavorException, IOException {
     73 
     74         return treeNode;
     75 
     76     }
     77 
     78 }
     79 
     80 class MySourceListener implements DragSourceListener {
     81     public void dragDropEnd(DragSourceDropEvent dragSourceDropEvent) {
     82         if (dragSourceDropEvent.getDropSuccess()) {
     83             // 拖拽动作结束的时候打印出移动节点的字符串
     84             int dropAction = dragSourceDropEvent.getDropAction();
     85             if (dropAction == DnDConstants.ACTION_MOVE) {
     86                 System.out.println("MOVE: remove node");
     87             }
     88         }
     89     }
     90 
     91     public void dragEnter(DragSourceDragEvent dragSourceDragEvent) {
     92         DragSourceContext context = dragSourceDragEvent.getDragSourceContext();
     93         int dropAction = dragSourceDragEvent.getDropAction();
     94         if ((dropAction & DnDConstants.ACTION_COPY) != 0) {
     95             context.setCursor(DragSource.DefaultCopyDrop);
     96         } else if ((dropAction & DnDConstants.ACTION_MOVE) != 0) {
     97             context.setCursor(DragSource.DefaultMoveDrop);
     98         } else {
     99             context.setCursor(DragSource.DefaultCopyNoDrop);
    100         }
    101     }
    102 
    103     public void dragExit(DragSourceEvent dragSourceEvent) {
    104     }
    105 
    106     public void dragOver(DragSourceDragEvent dragSourceDragEvent) {
    107     }
    108 
    109     public void dropActionChanged(DragSourceDragEvent dragSourceDragEvent) {
    110     }
    111 }
    112 
    113 class MyTargetListener implements DropTargetListener {
    114     public void dragEnter(DropTargetDragEvent dtde) {
    115 
    116     }
    117 
    118     public void dragOver(DropTargetDragEvent dtde) {
    119     }
    120 
    121     public void dropActionChanged(DropTargetDragEvent dtde) {
    122     }
    123 
    124     public void dragExit(DropTargetEvent dte) {
    125     }
    126 
    127     public void drop(DropTargetDropEvent dtde) {
    128         Transferable tr = dtde.getTransferable();// 使用该函数从Transferable对象中获取有用的数据
    129         String str = "";
    130         try {
    131             if (tr.isDataFlavorSupported(DataFlavor.stringFlavor)) {
    132                 str = tr.getTransferData(DataFlavor.stringFlavor).toString();
    133             }
    134         } catch (IOException ex) {
    135         } catch (UnsupportedFlavorException ex) {
    136         }
    137         System.out.println(str);
    138         DropTarget target = (DropTarget) dtde.getSource();
    139         JTextField filed = (JTextField) target.getComponent();
    140         if (str != null && str != "") {
    141             filed.setText(filed.getText() + str);
    142         }
    143     }
    144 }
  • 相关阅读:
    二维莫队的一个细节
    错失AK良机的测试48T3 Walk
    枚举二进制子集
    又是一次值得纪念的考试
    测试46
    值得纪念的测试43
    点分治模板理解
    牛客多校第三场 G Removing Stones(分治+线段树)
    牛客多校第三场 F Planting Trees
    HDU6621 K-th Closest Distance HDU2019多校训练第四场 1008(主席树+二分)
  • 原文地址:https://www.cnblogs.com/happyPawpaw/p/3103938.html
Copyright © 2020-2023  润新知