图形拖动例子

图形拖动例子

 

import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.LightweightSystem;
import org.eclipse.draw2d.MouseEvent;
import org.eclipse.draw2d.MouseListener;
import org.eclipse.draw2d.MouseMotionListener;
import org.eclipse.draw2d.Panel;
import org.eclipse.draw2d.RectangleFigure;
import org.eclipse.draw2d.XYLayout;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class Dnd1 {
	IFigure getRootFigure() {
		Panel panel = new Panel();
		panel.setLayoutManager(new XYLayout());
		RectangleFigure rFigure = new RectangleFigure();
		rFigure.setSize(55,55);
		rFigure.setBackgroundColor(ColorConstants.green);
		new Dnd(rFigure);
		panel.add(rFigure);
		return panel;
	}

	public static void main(String args[]) {
		Display display = Display.getDefault();
		Shell shell = new Shell();  
		shell.setSize(400, 300);
		shell.open();
		shell.setText("drag and drop example");
		LightweightSystem lws = new LightweightSystem(shell);
		lws.setContents(new Dnd1().getRootFigure());
		while (!shell.isDisposed ()) {
			if (!display.readAndDispatch ())
				display.sleep ();
		}
	}
}

class Dnd extends MouseMotionListener.Stub implements MouseListener {
	Point start;
	public Dnd(IFigure figure) 	{
		figure.addMouseMotionListener(this);
		figure.addMouseListener(this);
	}
	public void mouseReleased(MouseEvent e){
		Figure f = ((Figure)e.getSource());
		f.setCursor(null);
	}
	public void mouseClicked(MouseEvent e){}
	public void mouseDoubleClicked(MouseEvent e){}
	public void mousePressed(MouseEvent e) {
		Figure f = ((Figure)e.getSource());
		f.setCursor(Display.getCurrent().getSystemCursor(SWT.CURSOR_SIZEALL));
		start = e.getLocation();
	}
	public void mouseDragged(MouseEvent e) {
		if(start == null) {
			return;
		}
		Point p = e.getLocation();
		Dimension d = p.getDifference(start);
		start = p;
		Figure f = ((Figure)e.getSource());
		f.setBounds(f.getBounds().getTranslated(d.width, d.height));
	}
	
}

 

你可能感兴趣的:(例子)