All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.yaoqiang.graph.handler.YGraphTransferHandler Maven / Gradle / Ivy

package org.yaoqiang.graph.handler;

import java.awt.datatransfer.DataFlavor;

import javax.swing.JComponent;

import org.yaoqiang.graph.swing.YGraphComponent;

import com.mxgraph.swing.handler.mxGraphTransferHandler;
import com.mxgraph.swing.util.mxGraphTransferable;
import com.mxgraph.util.mxPoint;
import com.mxgraph.util.mxRectangle;
import com.mxgraph.view.mxGraph;

/**
 * YGraphTransferHandler
 * 
 * @author Shi Yaoqiang([email protected])
 */
public class YGraphTransferHandler extends mxGraphTransferHandler {

	private static final long serialVersionUID = 1L;

	public boolean canImport(JComponent comp, DataFlavor[] flavors)
	{
		for (int i = 0; i < flavors.length; i++)
		{
			if (flavors[i] != null
					&& (flavors[i].equals(mxGraphTransferable.dataFlavor) || flavors[i].isFlavorJavaFileListType())) // ==============start -- end==============
			{
				return true;
			}
		}

		return false;
	}
	
	protected boolean importGraphTransferable(YGraphComponent graphComponent,
			mxGraphTransferable gt)
	{
		boolean result = false;

		try
		{
			mxGraph graph = graphComponent.getGraph();
			double scale = graph.getView().getScale();
			mxRectangle bounds = gt.getBounds();
			double dx = 0, dy = 0;

			// Computes the offset for the placement of the imported cells
			if (location != null && bounds != null)
			{
				mxPoint translate = graph.getView().getTranslate();

				dx = location.getX() - (bounds.getX() + translate.getX())
						* scale;
				dy = location.getY() - (bounds.getY() + translate.getY())
						* scale;

				// Keeps the cells aligned to the grid
				dx = graph.snap(dx / scale);
				dy = graph.snap(dy / scale);
			}
			else
			{
				int gs = graph.getGridSize();

				dx = importCount * gs;
				dy = importCount * gs;
			}

			if (offset != null)
			{
				dx += offset.x;
				dy += offset.y;
			}

			// ==============start==============
			// Paste cells from popup menu
			if (location == null && bounds != null) {
				location = graphComponent.getPasteToPoint();
				if (location != null) {
					mxPoint translate = graph.getView().getTranslate();

					dx = location.getX() - (bounds.getX() + translate.getX()) * scale;
					dy = location.getY() - (bounds.getY() + translate.getY()) * scale;

					// Keeps the cells aligned to the grid
					dx = graph.snap(dx / scale);
					dy = graph.snap(dy / scale);
				}
			}
			// ==============end================
			
			importCells(graphComponent, gt, dx, dy);
			location = null;
			offset = null;
			result = true;

			// Requests the focus after an import
			graphComponent.requestFocus();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return result;
	}
	
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy