/**
   * Builds the JTree with the testgroups from which the user can select the tests to be run.
   *
   * @param testGroupList
   * @return JTree
   */
  public static JTree createTreeOfTestGroups(List<GroupOfTests> testGroupList, JPopupMenu popup) {

    JTree tree =
        new JTree(TreeModelFromListOfGroupsBuilder.GroupOfTestsToTreeModel(testGroupList)) {
          public String getToolTipText(MouseEvent evt) {

            if (getRowForLocation(evt.getX(), evt.getY()) == -1) return null;
            TreePath curPath = getPathForLocation(evt.getX(), evt.getY());

            if (curPath.getLastPathComponent() instanceof TestNode) {
              return ((TestNode) curPath.getLastPathComponent()).getToolTipText();
            }
            if (curPath.getLastPathComponent() instanceof GroupNode) {
              return ((GroupNode) curPath.getLastPathComponent()).getToolTipText();
            }
            return "No tooltip text";
          }
        };

    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    if (popup != null) {
      tree.setComponentPopupMenu(popup);
    }

    // Must be set or the getToolTipText method will never be called.
    //
    tree.setToolTipText("");

    DragSource ds = new DragSource();
    DragGestureRecognizer dgr =
        ds.createDefaultDragGestureRecognizer(
            tree, DnDConstants.ACTION_COPY, new TreeOfTestGroupsGestureListener(tree, ds));

    return tree;
  }
Beispiel #2
0
  private EntityPallet() {

    super("Model Builder");
    setType(Type.UTILITY);
    setAutoRequestFocus(false);
    // Make the x button do the same as the close button
    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    addWindowListener(FrameBox.getCloseListener("ShowModelBuilder"));

    tree = new MyTree();
    tree.setRootVisible(false);
    tree.setShowsRootHandles(true);
    DragSource dragSource = new DragSource();
    dragSource.createDefaultDragGestureRecognizer(tree, DnDConstants.ACTION_COPY, this);

    top = new DefaultMutableTreeNode();
    treeModel = new DefaultTreeModel(top);
    tree.setModel(treeModel);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

    // Create the tree scroll pane and add the tree to it
    treeView = new JScrollPane(tree);
    getContentPane().add(treeView);

    tree.setRowHeight(25);
    tree.setCellRenderer(new TreeCellRenderer());
    ToolTipManager.sharedInstance().registerComponent(tree);
    ToolTipManager.sharedInstance().setDismissDelay(600000);

    setLocation(GUIFrame.COL1_START, GUIFrame.TOP_START);
    setSize(GUIFrame.COL1_WIDTH, GUIFrame.HALF_TOP);
  }
Beispiel #3
0
 private void initialize() {
   // install drag n drop support
   dragSource = DragSource.getDefaultDragSource();
   dgRecognizer =
       dragSource.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_MOVE, this);
   // don't act on right mouse button
   dgRecognizer.setSourceActions(
       dgRecognizer.getSourceActions() & ~InputEvent.BUTTON3_MASK & ~InputEvent.BUTTON2_MASK);
   new DropTarget(this, new CDropTargetListener());
 }
Beispiel #4
0
 public DragDecoratorLabel(String s, Editor editor) {
   super(s, editor);
   DragSource dragSource = DragSource.getDefaultDragSource();
   dragSource.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY, this);
   try {
     dataFlavor = new DataFlavor(Editor.POSITIONABLE_FLAVOR);
   } catch (ClassNotFoundException cnfe) {
     cnfe.printStackTrace();
   }
 }
  /** Creates a new instance of AnimatedTileList */
  public AnimatedTileList(TiledLayerEditorComponent editorComponent) {
    this.editorComponent = editorComponent;
    this.imageResource = this.editorComponent.getTiledLayer().getImageResource();
    this.model = new AnimatedTileListDataModel();
    this.init();
    this.imageResource.addImageResourceListener(model);
    this.setModel(model);
    this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    this.setCellRenderer(new AnimatedTileListCellRenderer());
    this.setMinimumSize(new Dimension(this.editorComponent.getTiledLayer().getTileWidth(), 20));
    this.addListSelectionListener(
        new ListSelectionListener() {
          public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) return;
            AnimatedTileList.this.updatePaintTile();
          }
        });
    this.addFocusListener(
        new FocusAdapter() {
          public void focusGained(FocusEvent e) {
            AnimatedTileList.this.updatePaintTile();
          }
        });
    this.addMouseListener(
        new MouseAdapter() {
          public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
              handlePopup(e);
            }
          }

          public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
              handlePopup(e);
            }
          }

          public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() >= 2 && SwingUtilities.isLeftMouseButton(e)) {
              AnimatedTile tile = (AnimatedTile) AnimatedTileList.this.getSelectedValue();
              if (tile != null) {
                tile.getImageResource().getGameDesign().getMainView().requestEditing(tile);
              }
            }
          }
        });
    // DnD
    DragSource dragSource = new DragSource();
    DragGestureRecognizer dragGestureRecognizer =
        dragSource.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_MOVE, new DGL());
  }
Beispiel #6
0
 private void init() {
   FlowLayout fo = new FlowLayout();
   this.setLayout(fo);
   fo.setAlignment(FlowLayout.LEFT);
   iconLabel = new JLabel();
   displayNameField = new JLabel(this.mart.getDisplayName());
   this.add(iconLabel);
   this.add(displayNameField);
   this.refreshIcon();
   this.addMouseListener(this);
   DragSource ds = new DragSource();
   ds.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY, this);
   this.setBorder(BorderFactory.createLineBorder(this.getBackground()));
   this.setOpaque(true);
 }
 protected AbstractTreeTransferHandler(JTree tree, int action, boolean drawIcon) {
   this.tree = tree;
   drawImage = drawIcon;
   dragSource = new DragSource();
   dragSource.createDefaultDragGestureRecognizer(tree, action, this);
   dropTarget = new DropTarget(tree, action, this);
 }
Beispiel #8
0
  public void dragGestureRecognized(
      java.awt.dnd.DragGestureEvent
          event) { // System.out.println( "DragGestureListener.dragGestureRecognized" );
    final Object selected = getSelectedValue();
    if (selected != null) {
      sourceIndex = getSelectedIndex();
      java.awt.datatransfer.Transferable transfer =
          new TransferableObject(
              new TransferableObject.Fetcher() {
                /**
                 * This will be called when the transfer data is requested at the very end. At this
                 * point we can remove the object from its original place in the list.
                 */
                public Object getObject() {
                  ((javax.swing.DefaultListModel) getModel()).remove(sourceIndex);
                  return selected;
                } // end getObject
              }); // end fetcher

      // as the name suggests, starts the dragging
      dragSource.startDrag(event, java.awt.dnd.DragSource.DefaultLinkDrop, transfer, this);
    } else {
      // System.out.println( "nothing was selected");
    }
  } // end dragGestureRecognized
Beispiel #9
0
  /**
   * This method is called when the user initiates a drag operation. It attempts to start the drag.
   *
   * @param event the DragGestureEvent describing the gesture that has just occurred
   */
  public void dragGestureRecognized(DragGestureEvent event) {
    // Give subclasses a chance to stop the drag
    if (!isSelectionDraggable()) {
      return;
    }

    if (getSelectionCount() == 1) {
      TreePath path = getSelectionPath();
      if (path != null) {
        DefaultMutableTreeNode selection = (DefaultMutableTreeNode) path.getLastPathComponent();

        if (selection instanceof Transferable) {
          // Start the drag - a single Transferable node
          fDragSource.startDrag(
              event,
              (event.getDragAction() == DnDConstants.ACTION_COPY)
                  ? DragSource.DefaultCopyDrop
                  : DragSource.DefaultMoveDrop,
              (Transferable) selection,
              sDragSourceListener);
        }
      }
    } else if (getSelectionCount() > 1) {
      TreePath[] paths = getSelectionPaths();

      TransferableList selections = new TransferableList();

      for (int i = 0; i < paths.length; ++i) {
        DefaultMutableTreeNode selection = (DefaultMutableTreeNode) paths[i].getLastPathComponent();

        if (selection instanceof Transferable) {
          selections.add(selection);
        }
      }

      if (selections.size() > 0) {
        // Start the drag - a TransferableList of nodes
        fDragSource.startDrag(
            event,
            (event.getDragAction() == DnDConstants.ACTION_COPY)
                ? DragSource.DefaultCopyDrop
                : DragSource.DefaultMoveDrop,
            selections,
            sDragSourceListener);
      }
    }
  }
Beispiel #10
0
    /** This is where the ghost image is drawn */
    public void dragOver(final DropTargetDragEvent e) {
      if ((e == null)
          || (_raGhost == null)
          || (_ptLast == null)
          || (_ptOffset == null)
          || (_imgGhost == null)
          || (_raCueLine == null)) return;
      // Even if the mouse is not moving, this method is still invoked 10 times per second
      final Point pt = e.getLocation();
      if (pt == null) return;
      if (pt.equals(_ptLast)) return;

      // Try to determine whether the user is flicking the cursor right or left
      final int nDeltaLeftRight = pt.x - _ptLast.x;
      if (((_nLeftRight > 0) && (nDeltaLeftRight < 0))
          || ((_nLeftRight < 0) && (nDeltaLeftRight > 0))) _nLeftRight = 0;
      _nLeftRight += nDeltaLeftRight;
      _ptLast = pt;
      final Graphics2D g2 = (Graphics2D) getGraphics();
      if (g2 == null) return;

      // If a drag image is not supported by the platform, then draw my own drag image
      if (!DragSource.isDragImageSupported()) {
        JDragTree.this.paintImmediately(
            _raGhost.getBounds()); // Rub out the last ghost image and cue line
        // And remember where we are about to draw the new ghost image
        _raGhost.setRect(
            pt.x - _ptOffset.x, pt.y - _ptOffset.y, _imgGhost.getWidth(), _imgGhost.getHeight());
        g2.drawImage(
            _imgGhost,
            AffineTransform.getTranslateInstance(_raGhost.getX(), _raGhost.getY()),
            null);
      } else // Just rub out the last cue line
      JDragTree.this.paintImmediately(_raCueLine.getBounds());

      final TreePath path = getClosestPathForLocation(pt.x, pt.y);
      if (!(path == _pathLast)) {
        _nLeftRight = 0; // We've moved up or down, so reset left/right movement trend
        _pathLast = path;
        _timerHover.restart();
      }

      // In any case draw (over the ghost image if necessary) a cue line indicating where a drop
      // will occur
      final Rectangle raPath = getPathBounds(path);
      _raCueLine.setRect(0, raPath.y + (int) raPath.getHeight(), getWidth(), 2);

      g2.setColor(_colorCueLine);
      g2.fill(_raCueLine);

      // And include the cue line in the area to be rubbed out next time
      _raGhost = _raGhost.createUnion(_raCueLine);

      // Do this if you want to prohibit dropping onto the drag source
      if (path.equals(_pathSource)) e.rejectDrag();
      else e.acceptDrag(e.getDropAction());
    }
Beispiel #11
0
    /*
     * Drag Gesture Handler
     */
    @Override
    public void dragGestureRecognized(DragGestureEvent dge) {
      TreePath path = tree.getSelectionPath();

      if ((path == null) || (path.getPathCount() <= 1)) {
        return;
      }

      node = (TreeNode) path.getLastPathComponent();
      node.getNodeData().setCopy(false);
      transferable = new TransferableNode(node);

      if (Model.isResource(node.getNodeData()) || Model.isLiason(node.getNodeData())) {
        source.startDrag(dge, DragSource.DefaultLinkDrop, transferable, this);
      } else {
        source.startDrag(dge, DragSource.DefaultMoveDrop, transferable, this);
      }
    }
Beispiel #12
0
	public DroppableList() {
		// 初始化拖放源,第一个参数指定源对象,即本对象;第二个参数指定拖动支持的方式;
		// 第三个参数指定拖动发生时DragGestureListener的实现类,即本对象。
		dragSource.createDefaultDragGestureRecognizer(this,
				DnDConstants.ACTION_COPY_OR_MOVE, this);
		// 设置List的数据模型。
		DefaultListModel model = new DefaultListModel();
		setModel(model);
	}
Beispiel #13
0
  public DragLabel(String s) {
    this.setText(s);
    this.setOpaque(true);
    this.dragSource = DragSource.getDefaultDragSource();
    this.dgListener = new DGListener();
    this.dsListener = new DSListener();

    // component, action, listener
    this.dragSource.createDefaultDragGestureRecognizer(this, this.dragAction, this.dgListener);
  }
Beispiel #14
0
  public AndItem(boolean preview, Window w) {
    super(preview);
    this.w = w;
    FlowLayout fl = new FlowLayout(FlowLayout.CENTER, 1, 1);
    this.setLayout(fl);
    lefthand = new ParameterSlot(Parameter.Condition, "lefthand", preview, w);
    this.add(lefthand);
    JLabel la = new JLabel(" AND ");
    this.add(la);
    righthand = new ParameterSlot(Parameter.Condition, "righthand", preview, w);
    this.add(righthand);
    ToolTipItem tti = new ToolTipItem();
    tti.setToolTipText(
        "<html>This is an if item, if the specified condition <br> is fulfilled, the following block will be executed</html>");
    this.add(tti);
    this.setBackground(new Color(108, 45, 199));
    this.setBorder(BorderFactory.createLineBorder(Color.black));
    if (preview) {
      DragSource ds = new DragSource();
      ParameterDragGestureListener pdgl = new ParameterDragGestureListener();
      ds.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY, pdgl);
      ds.addDragSourceMotionListener(pdgl);
      ds.addDragSourceListener(
          new DragSourceListener() {
            @Override
            public void dropActionChanged(DragSourceDragEvent dsde) {}

            @Override
            public void dragOver(DragSourceDragEvent dsde) {}

            @Override
            public void dragExit(DragSourceEvent dse) {}

            @Override
            public void dragEnter(DragSourceDragEvent dsde) {}

            @Override
            public void dragDropEnd(DragSourceDropEvent dsde) {
              ImageMover.stop();
            }
          });
    }
  }
 public void init() {
   DragSource dragSource = DragSource.getDefaultDragSource();
   // 将srcLabel转换成拖放源,它能接受复制、移动两种操作
   dragSource.createDefaultDragGestureRecognizer(
       srcLabel,
       DnDConstants.ACTION_COPY_OR_MOVE,
       new DragGestureListener() {
         public void dragGestureRecognized(DragGestureEvent event) {
           // 将JLabel里的文本信息包装成Transferable对象
           String txt = srcLabel.getText();
           Transferable transferable = new StringSelection(txt);
           // 继续拖放操作,拖放过程中使用手状光标
           event.startDrag(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR), transferable);
         }
       });
   jf.add(new JScrollPane(srcLabel));
   jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   jf.pack();
   jf.setVisible(true);
 }
  public void dragGestureRecognized(DragGestureEvent event) {
    if (folderPanel.getMainFrame().getNoEventsMode()) return;

    FileTable fileTable = folderPanel.getFileTable();
    FileTableModel tableModel = fileTable.getFileTableModel();

    // Return (do not initiate drag) if mouse button2 or button3 was used
    if ((event.getTriggerEvent().getModifiers()
            & (InputEvent.BUTTON2_MASK | InputEvent.BUTTON3_MASK))
        != 0) return;

    // Do not use that to retrieve the current selected file as it is inaccurate: the selection
    // could have changed since the
    // the mouse was clicked.
    //        AbstractFile selectedFile = fileTable.getSelectedFile(false);
    //        // Return if selected file is null (could happen if '..' is selected)
    //        if(selectedFile==null)
    //            return;

    // Find out which row was clicked
    int clickedRow = fileTable.rowAtPoint(event.getDragOrigin());
    // Return (do not initiate drag) if the selected file is the parent folder '..'
    if (clickedRow == -1 || fileTable.isParentFolder(clickedRow)) return;

    // Retrieve the file corresponding to the clicked row
    AbstractFile selectedFile = tableModel.getFileAtRow(clickedRow);

    // Find out which files are to be dragged, based on the selected file and currenlty marked
    // files.
    // If there are some files marked, drag marked files only if the selected file is one of the
    // marked files.
    // In any other case, only drag the selected file.
    FileSet markedFiles;
    FileSet draggedFiles;
    if (tableModel.getNbMarkedFiles() > 0
        && (markedFiles = fileTable.getSelectedFiles()).contains(selectedFile)) {
      draggedFiles = markedFiles;
    } else {
      draggedFiles = new FileSet(fileTable.getCurrentFolder(), selectedFile);
    }

    // Set initial DnDContext information
    DnDContext.setDragInitiatedByMucommander(true);
    DnDContext.setDragInitiator(folderPanel);
    DnDContext.setDragGestureModifiersEx(event.getTriggerEvent().getModifiersEx());

    // Start dragging
    DragSource.getDefaultDragSource()
        .startDrag(event, null, new TransferableFileSet(draggedFiles), this);
    //        DragSource.getDefaultDragSource().startDrag(createCustomDragGestureEvent(event,
    // DnDConstants.ACTION_MOVE), null, new TransferableFileSet(draggedFiles), this);
  }
 /*
  * Drag Gesture Handler
  */
 public void dragGestureRecognized(DragGestureEvent dge) {
   TreePath path = sourceTree.getSelectionPath();
   if (path == null) {
     // We can't move an empty selection
     return;
   }
   oldNode = (DefaultMutableTreeNode) path.getLastPathComponent();
   transferable = new TransferableTreeNode(path);
   ObjectInspector.transferNode = transferable;
   try {
     source.startDrag(dge, DragSource.DefaultMoveDrop, transferable, this);
   } catch (Exception e) {
   }
 }
  public VariablePanel(String variableName, boolean preview, Window w) {
    super(preview);
    this.w = w;
    if (preview) {
      w.spellItems.put(variableName, this);
    }
    this.s = variableName;
    JLabel jl = new JLabel(variableName);
    this.setLayout(new BorderLayout());
    this.add(jl, BorderLayout.CENTER);
    this.setBorder(BorderFactory.createLineBorder(Color.black));
    this.setBackground(Color.lightGray);
    DragSource ds = new DragSource();
    VariableDragGestureListener pdgl = new VariableDragGestureListener();
    ds.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY, pdgl);
    ds.addDragSourceMotionListener(pdgl);
    ds.addDragSourceListener(
        new DragSourceListener() {
          @Override
          public void dropActionChanged(DragSourceDragEvent dsde) {}

          @Override
          public void dragOver(DragSourceDragEvent dsde) {}

          @Override
          public void dragExit(DragSourceEvent dse) {}

          @Override
          public void dragEnter(DragSourceDragEvent dsde) {}

          @Override
          public void dragDropEnd(DragSourceDropEvent dsde) {
            ImageMover.stop();
          }
        });
  }
  public void dragGestureRecognized(DragGestureEvent evt) {
    if (files == null) return;
    if (files.length <= 0) {
      return;
    }
    Icon icn = files[0].getIcon(false);
    Toolkit tk = Toolkit.getDefaultToolkit();
    if (icn == null) icn = new EmptyIcon();
    Dimension dim = tk.getBestCursorSize(icn.getIconWidth(), icn.getIconHeight());

    // set up drag image
    if (DragSource.isDragImageSupported()) {
      BufferedImage buff =
          new BufferedImage(dim.width + 100, dim.height, BufferedImage.TYPE_INT_ARGB);
      Graphics graphics = buff.getGraphics();
      Color color = graphics.getColor();
      icn.paintIcon(null, graphics, 0, 0);
      graphics.setColor(color);
      graphics.setColor(Color.RED);
      graphics.drawString(files.length + " Elements", icn.getIconWidth(), dim.height / 2);
      try {
        evt.startDrag(
            DragSource.DefaultCopyDrop,
            buff,
            new Point(0, 0),
            new FileTransferable(files, table.getTableModel()),
            this);
      } catch (IOException ex) {
        Logger.getLogger(FileDragGestureListener.class.getName()).log(Level.SEVERE, null, ex);
      }
    } else {
      BufferedImage buff = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_ARGB);
      Graphics graphics = buff.getGraphics();
      icn.paintIcon(null, graphics, 0, 0);
      try {
        cursor = tk.createCustomCursor(buff, new Point(0, 0), "tempcursor");
        evt.startDrag(
            cursor,
            null,
            new Point(0, 0),
            new FileTransferable(files, table.getTableModel()),
            this);
      } catch (IOException ex) {
        Logger.getLogger(FileDragGestureListener.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
Beispiel #20
0
  /** convenience routine for setting up drag and drop */
  private void setupDnD() {

    // gesture recognizer establishes what action starts the dnd

    DragGestureRecognizer dgr =
        dragSource.createDefaultDragGestureRecognizer(
            this, // DragSource
            DnDConstants.ACTION_COPY, // specifies valid actions
            this // DragGestureListener
            );

    /*
     * Eliminates right mouse clicks as valid actions - useful especially if
     * you implement a JPopupMenu for the JTree
     */
    dgr.setSourceActions(dgr.getSourceActions() & ~InputEvent.BUTTON3_MASK);
  }
Beispiel #21
0
  public DragLabel(String s, int a) {
    if (a != DnDConstants.ACTION_NONE
        && a != DnDConstants.ACTION_COPY
        && a != DnDConstants.ACTION_MOVE
        && a != DnDConstants.ACTION_COPY_OR_MOVE
        && a != DnDConstants.ACTION_LINK) throw new IllegalArgumentException("action" + a);

    this.dragAction = a;
    this.setText(s);
    this.setOpaque(true);
    this.dragSource = DragSource.getDefaultDragSource();
    this.dgListener = new DGListener();
    this.dsListener = new DSListener();

    // component, action, listener
    this.dragSource.createDefaultDragGestureRecognizer(this, this.dragAction, this.dgListener);
  }
  public PaletteElementView(
      PaletteElementGraphicalRepresentation aGraphicalRepresentation,
      DrawingController<PaletteDrawing> controller) {
    super(aGraphicalRepresentation, controller);
    this.dgListener = new DGListener();
    this.dragSource = DragSource.getDefaultDragSource();
    this.dsListener = new DSListener();
    this.paletteController = controller;

    dgr = createDragGestureRecognizer();
    // component, action, listener
    enableDragging();

    if (aGraphicalRepresentation.getToolTipText() != null) {
      setToolTipText(aGraphicalRepresentation.getToolTipText());
    }
  }
 /* Methods for DragGestureListener */
 public final void dragGestureRecognized(DragGestureEvent dge) {
   TreePath path = tree.getSelectionPath();
   if (path != null) {
     draggedPath = path;
     draggedNodeParentPath = path.getParentPath();
     if (drawImage) {
       Rectangle pathBounds = tree.getPathBounds(path); // getpathbounds of selectionpath
       JComponent lbl =
           (JComponent)
               tree.getCellRenderer()
                   .getTreeCellRendererComponent(
                       tree,
                       draggedPath.getLastPathComponent(),
                       false,
                       tree.isExpanded(path),
                       false,
                       0,
                       false); // returning the label
       lbl.setBounds(pathBounds); // setting bounds to lbl
       image =
           new BufferedImage(
               lbl.getWidth(),
               lbl.getHeight(),
               java.awt.image.BufferedImage
                   .TYPE_INT_ARGB_PRE); // buffered image reference passing the label's ht and
                                        // width
       Graphics2D graphics = image.createGraphics(); // creating the graphics for buffered image
       graphics.setComposite(
           AlphaComposite.getInstance(
               AlphaComposite.SRC_OVER, 0.5f)); // Sets the Composite for the Graphics2D context
       lbl.setOpaque(false);
       lbl.paint(graphics); // painting the graphics to label
       graphics.dispose();
     }
     dragSource.startDrag(
         dge,
         DragSource.DefaultMoveNoDrop,
         image,
         new Point(0, 0),
         new TransferableNode(draggedPath),
         this);
   }
 }
Beispiel #24
0
  /** Starts the drag process */
  @Override
  public void dragGestureRecognized(DragGestureEvent dge) {
    // Get the selected nodes (even if single select)
    List<File> list = getSelectedFileList();
    if ((list == null) || (list.size() < 1)) {
      return;
    }
    FileNodes fn = new FileNodes(list);

    // Get the Transferable Object
    Transferable transferable = fn;

    // begin the drag
    try {
      dragSource.startDrag(dge, DragSource.DefaultCopyDrop, transferable, this);
    } catch (InvalidDnDOperationException e) {
      e.printStackTrace();
    }
  }
 /**
  * Enables drag operations on the specified component. This class will be notified wheneven drag
  * operations are performed on the component.
  *
  * @param c the component for which to add 'drag' support
  */
 public void enableDrag(Component c) {
   DragSource dragSource = DragSource.getDefaultDragSource();
   dragSource.createDefaultDragGestureRecognizer(
       c, DnDConstants.ACTION_COPY | DnDConstants.ACTION_MOVE | DnDConstants.ACTION_LINK, this);
 }
Beispiel #26
0
/**
 * 支持拖放的List:可以将文件拖放到List中,也可以把List中的项拖放到文件系统或者文本框中。
 * 支持拖放必须实现3个接口:DropTargetListener、DragSourceListener和DragGestureListener。
 * 当拖动List中的数据开始时,DragGestureListener定义的方法被调用。
 * 当拖动List中的数据过程中,DragSourceListener定义的方法被调用。
 * 当往List中放置数据时,DragSourceListener定义的方法被调用。
 */
public class DroppableList extends JList implements DropTargetListener,
		DragSourceListener, DragGestureListener {
	// 拖放的目的地,即放置点,本List接收放置drop操作
	DropTarget dropTarget = new DropTarget(this, this);

	// 使用默认的拖放源
	DragSource dragSource = DragSource.getDefaultDragSource();

	public DroppableList() {
		// 初始化拖放源,第一个参数指定源对象,即本对象;第二个参数指定拖动支持的方式;
		// 第三个参数指定拖动发生时DragGestureListener的实现类,即本对象。
		dragSource.createDefaultDragGestureRecognizer(this,
				DnDConstants.ACTION_COPY_OR_MOVE, this);
		// 设置List的数据模型。
		DefaultListModel model = new DefaultListModel();
		setModel(model);
	}

	// 下面五个方法实现了DragSourceListener接口定义的方法,当拖动本对象的数据到其他地方时,调用这些方法。
	public void dragDropEnd(DragSourceDropEvent DragSourceDropEvent) {
		System.out
				.println("method: dragDropEnd(DragSourceDropEvent DragSourceDropEvent)");
	}

	public void dragEnter(DragSourceDragEvent DragSourceDragEvent) {
		System.out
				.println("method: dragEnter(DragSourceDragEvent DragSourceDragEvent)");
	}

	public void dragExit(DragSourceEvent DragSourceEvent) {
		System.out.println("method: dragExit(DragSourceEvent DragSourceEvent)");
	}

	public void dragOver(DragSourceDragEvent DragSourceDragEvent) {
		// System.out.println("method: dragOver(DragSourceDragEvent
		// DragSourceDragEvent) called!");
	}

	public void dropActionChanged(DragSourceDragEvent DragSourceDragEvent) {
		System.out
				.println("method: dropActionChanged(DragSourceDragEvent DragSourceDragEvent)");
	}

	// 下面5个方法实现了DropTargetListener接口定义的方法,当拖动东西放进本对象时,这些方法被调用。
	public void dragEnter(DropTargetDragEvent dropTargetDragEvent) {
		System.out
				.println("method: dragEnter(DropTargetDragEvent dropTargetDragEvent)");
		dropTargetDragEvent.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
	}

	public void dragExit(DropTargetEvent dropTargetEvent) {
		System.out.println("method: dragExit(DropTargetEvent dropTargetEvent)");
	}

	public void dragOver(DropTargetDragEvent dropTargetDragEvent) {
		// System.out.println("method: dragOver(DropTargetDragEvent
		// dropTargetDragEvent) called!");
	}

	public void dropActionChanged(DropTargetDragEvent dropTargetDragEvent) {
		System.out
				.println("method: dropActionChanged(DropTargetDragEvent dropTargetDragEvent)");
	}

	/**
	 * 当拖动系统中的文件放置drop到该List中时,调用此方法。
	 */
	public synchronized void drop(DropTargetDropEvent dropTargetDropEvent) {
		System.out
				.println("method: drop(DropTargetDropEvent dropTargetDropEvent)");
		try {
			// 获取传入的Transfer对象
			Transferable tr = dropTargetDropEvent.getTransferable();
			// 如果Transfer对象支持文件放置到java平台,则进行下一步处理
			if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
				// 使用“拷贝、移动”方式接收放置操作。
				dropTargetDropEvent
						.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
				// 从Transfer中取数据,得到的是一个文件列表。即可以一次拖放多个文件
				java.util.List fileList = (java.util.List) tr
						.getTransferData(DataFlavor.javaFileListFlavor);
				Iterator iterator = fileList.iterator();
				while (iterator.hasNext()) {
					// 将拖放进来的文件的信息添加到List的数据模型中
					File file = (File) iterator.next();
					Hashtable hashtable = new Hashtable();
					hashtable.put("name", file.getName());
					hashtable.put("url", file.toURL().toString());
					hashtable.put("path", file.getAbsolutePath());
					((DefaultListModel) getModel()).addElement(hashtable);
				}
				// 放置操作成功结束
				dropTargetDropEvent.getDropTargetContext().dropComplete(true);
			} else {
				// Transferable对象不支持文件放置到java中,拒绝。
				System.err.println("Rejected");
				dropTargetDropEvent.rejectDrop();
			}
		} catch (IOException io) {
			io.printStackTrace();
			dropTargetDropEvent.rejectDrop();
		} catch (UnsupportedFlavorException ufe) {
			ufe.printStackTrace();
			dropTargetDropEvent.rejectDrop();
		}
	}

	/**
	 * 当从List中选择一项拖放到文件系统或者其他地方时,调用此方法。 这是DragGestureListener接口定义的方法。
	 */
	public void dragGestureRecognized(DragGestureEvent dragGestureEvent) {
		System.out
				.println("method: dragGestureRecognized(DragGestureEvent dragGestureEvent)");
		if (getSelectedIndex() == -1)
			return;
		// 获得被选择的项的数据。
		Object obj = getSelectedValue();
		if (obj == null) {
			// 如果没有选择列表中的项,则不能视为一个拖动,则蜂鸣。
			System.out.println("Nothing selected - beep");
			getToolkit().beep();
		} else {
			// 将List中被选择的项打包成一个Transfer对象
			Hashtable table = (Hashtable) obj;
			FileSelection transferable = new FileSelection(new File(
					(String) table.get("path")));
			// 开始拖放,第一个参数为拖放时的光标;第二个参数为被拖放的数据对象;第三个是拖放拖放源侦听器
			dragGestureEvent.startDrag(DragSource.DefaultCopyDrop,
					transferable, this);
		}
	}

	/**
	 * 内部类,定义了一个支持文件拖放的Transfer对象。 它继承Vector,表示它可以一次传送多个文件
	 */
	class FileSelection extends Vector implements Transferable {
		final static int FILE = 0;

		final static int STRING = 1;

		final static int PLAIN = 2;

		// 定义该Transfer能够传送的数据类型,包括文件、字符串和无格式的文本。
		DataFlavor flavors[] = { DataFlavor.javaFileListFlavor,
				DataFlavor.stringFlavor, DataFlavor.plainTextFlavor };

		public FileSelection(File file) {
			// 将文件保存
			addElement(file);
		}

		/* 返回该Transfer能够传递的数据类型 */
		public synchronized DataFlavor[] getTransferDataFlavors() {
			return flavors;
		}

		/* 判断该Transfer是否支持flavor数据类型的传送 */
		public boolean isDataFlavorSupported(DataFlavor flavor) {
			boolean b = false;
			b |= flavor.equals(flavors[FILE]);
			b |= flavor.equals(flavors[STRING]);
			b |= flavor.equals(flavors[PLAIN]);
			return (b);
		}

		/**
		 * 返回Transfer对象中封装的数据
		 */
		public synchronized Object getTransferData(DataFlavor flavor)
				throws UnsupportedFlavorException, IOException {
			if (flavor.equals(flavors[FILE])) {
				// 如果是要获取文件数据、则将自己返回,是一个文件的Vector。
				System.out.println("return flavors[FILE]");
				return this;
			} else if (flavor.equals(flavors[PLAIN])) {
				// 如果是要获取一个文本,则将第一个文件的文件内容的流的引用返回。
				System.out.println("return flavors[PLAIN]");
				return new StringReader(((File) elementAt(0)).getAbsolutePath());
			} else if (flavor.equals(flavors[STRING])) {
				// 如果是要获取一个字符串,则将第一个文件的文件路径名返回
				System.out.println("return flavors[STRING]");
				return ((File) elementAt(0)).getAbsolutePath();
			} else {
				throw new UnsupportedFlavorException(flavor);
			}
		}
	}

	/**
	 * 组件拖放的基本原理:
	 * (1)从List中拖动时,dragGestureRecognized方法将JList中被选择的项打包成一个Transferable对象。
	 * (2)放置数据到List中时,drop方法将Transferable对象中的数据放到List中。
	 */
}
 @Override
 public void dragGestureRecognized(DragGestureEvent evt) {
   Transferable transferable = new StringTransferable(String.valueOf(imageType.getId()));
   dragSource.startDrag(evt, DragSource.DefaultCopyDrop, transferable, this);
 }
 public DraggableLabel(ImageType imageType) throws IOException {
   super(new ImageIcon(imageType.getImage()));
   this.imageType = imageType;
   dragSource = new DragSource();
   dragSource.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, this);
 }
Beispiel #29
0
 public void dragExit(final DropTargetEvent e) {
   if (!DragSource.isDragImageSupported()) {
     JDragTree.this.repaint(_raGhost.getBounds());
   }
 }
Beispiel #30
0
  /**
   * Creates a new JTree that supports dragging tree nodes. The specified TreeModel is used as the
   * data model.
   *
   * @param model the TreeModel to use as the data model
   */
  public DraggableTree(TreeModel model) {
    super(model);

    fDragSource.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, this);
  }