
package draganddrop;

import org.gnu.gdk.DragAction;
import org.gnu.gdk.DragContext;
import org.gnu.gdk.ModifierType;
import org.gnu.gtk.Button;
import org.gnu.gtk.DestDefaults;
import org.gnu.gtk.Gtk;
import org.gnu.gtk.HBox;
import org.gnu.gtk.Label;
import org.gnu.gtk.SelectionData;
import org.gnu.gtk.TargetEntry;
import org.gnu.gtk.TargetFlags;
import org.gnu.gtk.Widget;
import org.gnu.gtk.Window;
import org.gnu.gtk.WindowType;
import org.gnu.gtk.event.DragDestinationListener;
import org.gnu.gtk.event.DragSourceListener;
import org.gnu.gtk.event.LifeCycleEvent;
import org.gnu.gtk.event.LifeCycleListener;

/**
 */
public class DnDExample1 {
	
	private Window win;
	
	private TargetEntry[] target = new TargetEntry[] {
		new TargetEntry("text/plain", TargetFlags.NO_RESTRICTION, 0)
	};
	
	public DnDExample1() {
		win = new Window( WindowType.TOPLEVEL );
		win.setBorderWidth(25);
		win.setTitle("Java-Gnome Drag and Drop Example");
		win.addListener(new LifeCycleListener() {
			public void lifeCycleEvent(LifeCycleEvent event) {}
			public boolean lifeCycleQuery(LifeCycleEvent event) {
				if (event.isOfType(LifeCycleEvent.Type.DESTROY) || 
						event.isOfType(LifeCycleEvent.Type.DELETE)) {
						Gtk.mainQuit();
				}
				return false;
			}
		});
		
		
		HBox box = new HBox(true, 0);
		win.add(box);
		
		packSendingButton(box, "Left Source Text");
		packReceivingButton(box, "Destination Window");
		packSendingButton(box, "Right Source Text");
		
		win.showAll();
	}
	
	private void packSendingButton(HBox box, String text) {
		Button button = new Button(text, false);
		box.packStart(button, true, false, 0);
		button.addListener(new DragSourceListener() {
			public void dragBegin(Widget widget, DragContext dc) {}
			public void dragMotion(Widget widget, DragContext dc, int x, int y) {}
			public void getDragData(Widget widget, DragContext dc, SelectionData sd, int info) {
				Button but = (Button)widget;
				Label label = (Label)but.getChild();
				String text = label.getText();
				sd.setText(text);
			}
			public void deleteDragData(Widget widget, DragContext dc) {}
			public void dragDrop(Widget widget, DragContext dc, int x, int y) {}
			public void dragEnd(Widget widget, DragContext dc) {}
			
		});
		button.setDragSource(ModifierType.BUTTON1_MASK, target, DragAction.COPY);
	}
	
	private void packReceivingButton(HBox box, String text) {
		Button button = new Button(text, false);
		box.packStart(button, true, false, 0);
		button.addListener(new DragDestinationListener() {
			public void dataReceived(Widget widget, DragContext dc, SelectionData data, int targetInfo) {
				Button but = (Button)widget;
				Label label = (Label)but.getChild();
				label.setText(data.getText());
			}
		});
		button.setDragDestination(DestDefaults.MOTION.or(DestDefaults.HIGHLIGHT.or(DestDefaults.DROP)),
				target, DragAction.COPY);
	}
	
	public static void main(String[] args) {
		Gtk.init(args);
		DnDExample1 example = new DnDExample1();
		Gtk.main();
	}
}
