Java Example Program/ Sample Source Code
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceMotionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.TransferHandler;
public class DragMouseMovedExample extends JPanel implements Transferable,
MouseListener {
public static void main(String[] s) {
JFrame f = new JFrame();
f.setSize(200, 200);
f.getContentPane().setLayout(new BorderLayout());
DragMouseMovedExample d = new DragMouseMovedExample();
f.getContentPane().add(d, BorderLayout.NORTH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public DragMouseMovedExample() {
this.setTransferHandler(new TransferHandler() {
@Override
protected Transferable createTransferable(JComponent c) {
return (DragMouseMovedExample) c;
}
@Override
public boolean canImport(JComponent comp,
DataFlavor[] transferFlavors) {
return false;
}
@Override
public int getSourceActions(JComponent c) {
return MOVE;
}
});
DragSource.getDefaultDragSource().addDragSourceMotionListener(
new DragSourceMotionListener() {
public void dragMouseMoved(DragSourceDragEvent dsde) {
System.out.println("DRAGMOUSEMOVED");
}
});
this.setPreferredSize(new Dimension(200, 100));
this.addMouseListener(this);
}
@Override
public void mousePressed(MouseEvent e) {
if (e.getX() > getWidth() / 2) {
System.out.println("EXPORT");
this.getTransferHandler().exportAsDrag(this, e,
TransferHandler.MOVE);
} else {
System.out.println("no Export");
}
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.GREEN);
g.fillRect(0, 0, getWidth() / 2, getHeight());
g.setColor(Color.RED);
g.fillRect(getWidth() / 2, 0, getWidth(), getHeight());
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return false;
}
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] {};
}
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
return new Object();
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
} |
|
|