Recreation of previously created elements on creation of new elements SWT Draw2d - java

I've written code that allows drag and drop onto a canvas. On 'dropping', a RectangleFigure is drawn on the canvas at that point. The problem is that when I drop onto the canvas for the second time, another copy of the first dropped element is made on the screen. Similarly, the third time, the first two elements are recreated.(We know this, to be true because if you drag one of the elements from it's original position, you can see the recreated elements underneath it) Can someone please tell me how to prevent this recreation from taking place? *I have added short testable code illustrating the problem
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.RectangleFigure;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.wb.swt.SWTResourceManager;
import org.eclipse.swt.widgets.Label;
/**
*
*Shortest complete testable code demonstrating the repeated creation problem
*/
public class RepeatDrop
{
/**
* Launch the application.
*
* #param args
*/
private Shell shell;
private Display display;
private Menu menu;
private Group grpPalette;
private final Label lblUnicorn;
private Group grpCanvas;
private final Canvas canvas;
public static void main(String args[]) {
new RepeatDrop();
}
/**
* Create the shell.
*
* #param display
*/
public RepeatDrop() {
display = new Display();
shell = new Shell(display);
shell.setText("SWT Application");
shell.setSize(450, 393);
Group grpPalette = new Group(shell, SWT.NONE);
grpPalette.setText("Palette");
grpPalette.setBounds(0, 0, 88, 325);
lblUnicorn = new Label(grpPalette, SWT.BORDER | SWT.HORIZONTAL
| SWT.CENTER);
lblUnicorn.setText("UNICORN");
// ADDED A FINAL HERE!!
lblUnicorn.setAlignment(SWT.CENTER);
lblUnicorn.setBounds(10, 24, 68, 53);
final Group grpCanvas = new Group(shell, SWT.NONE);
grpCanvas.setText("Canvas");
grpCanvas.setBounds(94, 0, 330, 325);
canvas = new Canvas(grpCanvas, SWT.NONE);
canvas.setBackground(SWTResourceManager.getColor(253, 245, 230));
canvas.setBounds(10, 20, 320, 295);
LightweightSystem lws = new LightweightSystem(canvas); //
final IFigure panel = new Figure(); //
lws.setContents(panel); //
DragSource dragSource1 = new DragSource(lblUnicorn, DND.DROP_COPY);
Transfer[] transfers1 = new Transfer[] { TextTransfer.getInstance() };
dragSource1.setTransfer(transfers1);
dragSource1.addDragListener(new DragSourceListener() {
public void dragStart(DragSourceEvent event) {
if (lblUnicorn.getText().length() == 0) {
event.doit = false;
}
}
public void dragSetData(DragSourceEvent event) {
if (TextTransfer.getInstance().isSupportedType (event.dataType)) {
event.data = lblUnicorn.getText();
}
}
public void dragFinished(DragSourceEvent event) {
}
});
Transfer[] types = new Transfer[] { TextTransfer.getInstance() };
DropTarget dropTarget = new DropTarget(canvas, DND.DROP_COPY
| DND.DROP_DEFAULT);
dropTarget.setTransfer(types);
dropTarget.addDropListener(new DropTargetListener() {
public void dragEnter(DropTargetEvent event) {
if (event.detail == DND.DROP_DEFAULT) {
if ((event.operations & DND.DROP_COPY) != 0) {
event.detail = DND.DROP_COPY;
} else {
event.detail = DND.DROP_NONE;
}
}
}
public void dragLeave(DropTargetEvent event) {
}
public void dragOperationChanged(DropTargetEvent event) {
}
public void dragOver(DropTargetEvent event) {
}
public void drop(DropTargetEvent event) {
}
public void dropAccept(final DropTargetEvent event)
{
if (TextTransfer.getInstance().isSupportedType(
event.currentDataType)) {
String d = (String) TextTransfer.getInstance()
.nativeToJava(event.currentDataType);
final String finald= d;
GC gc = new GC(canvas);
canvas.redraw();
canvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
org.eclipse.swt.graphics.Point droppoint = canvas.toControl(event.x, event.y);
//DRAW 2D SECTION
RectangleFigure node1 = new RectangleFigure();
Rectangle rect=new Rectangle(droppoint.x, droppoint.y, 20, 20);
Rectangle rect2=new Rectangle(droppoint.x, droppoint.y, 100, 25);
node1.setBounds(rect);
node1.setBackgroundColor(ColorConstants.cyan);
org.eclipse.draw2d.Label droppedName=
new org.eclipse.draw2d.Label(finald);
droppedName.setLocation(new Point(droppoint.x, droppoint.y)); //draw2d. point
droppedName.setBounds(rect2);
node1.add(droppedName);
panel.add(node1);
panel.add(droppedName);
Dragger fig = new Dragger(node1);
Dragger caption = new Dragger(droppedName);
//DRAW 2D SECTION
}
});
}
}
});
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
static class Dragger extends MouseMotionListener.Stub implements MouseListener
{
public Dragger(IFigure figure){
figure.addMouseMotionListener(this);
figure.addMouseListener(this);
}
Point last;
public void mouseReleased(MouseEvent e){
}
public void mouseClicked(MouseEvent e){
}
public void mouseDoubleClicked(MouseEvent e){
}
public void mousePressed(MouseEvent e){
last = e.getLocation();
}
public void mouseDragged(MouseEvent e){
Point p = e.getLocation();
Dimension delta = p.getDifference(last);
{
last = p;
Figure f = ((Figure)e.getSource());
f.setBounds(f.getBounds().getTranslated(delta.width, delta.height));
}
}
}
}

Your issue is caused by the fact that you add a new PaintListener each time you add a new figure. That isn't necessary. In fact, you don't need to add any PaintListener at all. The LightweightSystem will take care of that for you.
Here is your code now working fine:
public class RepeatDrop
{
private Shell shell;
private Display display;
private final Label lblUnicorn;
private final Canvas canvas;
public static void main(String args[])
{
new RepeatDrop();
}
public RepeatDrop()
{
display = new Display();
shell = new Shell(display);
shell.setText("SWT Application");
shell.setLayout(new GridLayout(2, false));
Group grpPalette = new Group(shell, SWT.NONE);
grpPalette.setText("Palette");
grpPalette.setLayout(new GridLayout());
grpPalette.setLayoutData(new GridData(SWT.BEGINNING, SWT.FILL, false, true));
lblUnicorn = new Label(grpPalette, SWT.BORDER | SWT.HORIZONTAL | SWT.CENTER);
lblUnicorn.setText("UNICORN");
// ADDED A FINAL HERE!!
lblUnicorn.setAlignment(SWT.CENTER);
final Group grpCanvas = new Group(shell, SWT.NONE);
grpCanvas.setText("Canvas");
grpCanvas.setLayout(new GridLayout());
grpCanvas.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
canvas = new Canvas(grpCanvas, SWT.NONE);
canvas.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
LightweightSystem lws = new LightweightSystem(canvas); //
final IFigure panel = new Figure(); //
lws.setContents(panel); //
DragSource dragSource1 = new DragSource(lblUnicorn, DND.DROP_COPY);
Transfer[] transfers1 = new Transfer[] { TextTransfer.getInstance() };
dragSource1.setTransfer(transfers1);
dragSource1.addDragListener(new DragSourceListener()
{
public void dragStart(DragSourceEvent event)
{
if (lblUnicorn.getText().length() == 0)
{
event.doit = false;
}
}
public void dragSetData(DragSourceEvent event)
{
if (TextTransfer.getInstance().isSupportedType(event.dataType))
{
event.data = lblUnicorn.getText();
}
}
public void dragFinished(DragSourceEvent event)
{
}
});
Transfer[] types = new Transfer[] { TextTransfer.getInstance() };
DropTarget dropTarget = new DropTarget(canvas, DND.DROP_COPY | DND.DROP_DEFAULT);
dropTarget.setTransfer(types);
dropTarget.addDropListener(new DropTargetListener()
{
public void dragEnter(DropTargetEvent event)
{
if (event.detail == DND.DROP_DEFAULT)
{
if ((event.operations & DND.DROP_COPY) != 0)
{
event.detail = DND.DROP_COPY;
}
else
{
event.detail = DND.DROP_NONE;
}
}
}
public void dragLeave(DropTargetEvent event)
{
}
public void dragOperationChanged(DropTargetEvent event)
{
}
public void dragOver(DropTargetEvent event)
{
}
public void drop(DropTargetEvent event)
{
}
public void dropAccept(final DropTargetEvent event)
{
if (TextTransfer.getInstance().isSupportedType(event.currentDataType))
{
String d = (String) TextTransfer.getInstance().nativeToJava(event.currentDataType);
org.eclipse.swt.graphics.Point droppoint = canvas.toControl(event.x, event.y);
// DRAW 2D SECTION
RectangleFigure node1 = new RectangleFigure();
Rectangle rect = new Rectangle(droppoint.x, droppoint.y, 20, 20);
Rectangle rect2 = new Rectangle(droppoint.x, droppoint.y, 100, 25);
node1.setBounds(rect);
node1.setBackgroundColor(ColorConstants.cyan);
org.eclipse.draw2d.Label droppedName = new org.eclipse.draw2d.Label(d);
droppedName.setLocation(new Point(droppoint.x, droppoint.y)); // draw2d.
// point
droppedName.setBounds(rect2);
node1.add(droppedName);
panel.add(node1);
panel.add(droppedName);
new Dragger(node1);
new Dragger(droppedName);
canvas.redraw();
}
}
});
shell.pack();
shell.setSize(400, 300);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
}
static class Dragger extends MouseMotionListener.Stub implements MouseListener
{
public Dragger(IFigure figure)
{
figure.addMouseMotionListener(this);
figure.addMouseListener(this);
}
Point last;
public void mouseReleased(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseDoubleClicked(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
last = e.getLocation();
}
public void mouseDragged(MouseEvent e)
{
Point p = e.getLocation();
Dimension delta = p.getDifference(last);
{
last = p;
Figure f = ((Figure) e.getSource());
f.setBounds(f.getBounds().getTranslated(delta.width, delta.height));
}
}
}
}
Please have a look at the way I used Layouts. It's far more reliable and will work better on different window sizes and screen resolutions.
Please also read this: Understanding Layouts in SWT

Related

SWT Mouse Events - Desktop vs Mobile

How do the effects of Mouse Events differ between standard Windows Desktop application usage and Windows Tablet usage?
We have created an application that creates a pop-up virtual keyboard when certain text fields gain focus. This virtual keyboard can then be clicked on to type into the text field without causing the text field to lose focus.
This works correctly when using a mouse on a standard desktop PC. However, when running on a mobile device such as a Windows Tablet and using touch commands, the keyboard behaves differently, losing focus.
We have been under the impression that mobile touch commands largely simulated mouse click events, although that does not seem to be the case here. Why do these two input methods work differently? How can we make our keyboard work identically on both types of platforms?
A small test program follows:
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class KeyboardEventTest {
private Kbd kbd = null;
protected Shell shell;
private Label lblNoEvent;
private Text txtNoEvent;
private Label lblYesEvent;
private Text txtYesEvent;
private ControlListener _parentControlListener = new ControlListener() {
#Override
public void controlResized(ControlEvent e) {
}
#Override
public void controlMoved(ControlEvent e) {
if(kbd != null)
kbd.positionRelativeToControl();
}
};
public static void main(String[] args) {
try {
KeyboardEventTest window = new KeyboardEventTest();
window.open();
}
catch (Exception e) {
e.printStackTrace();
}
}
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while(!shell.isDisposed()) {
if(!display.readAndDispatch()) {
display.sleep();
}
}
}
protected void createContents() {
shell = new Shell();
shell.setSize(450, 300);
shell.setText("Keyboard Event Test");
GridLayout gl_shell = new GridLayout();
gl_shell.numColumns = 2;
shell.setLayout(gl_shell);
lblNoEvent = new Label(shell, SWT.NONE);
lblNoEvent.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblNoEvent.setText("No Event");
txtNoEvent = new Text(shell, SWT.BORDER);
txtNoEvent.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
lblYesEvent = new Label(shell, SWT.NONE);
lblYesEvent.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
lblYesEvent.setText("Event");
txtYesEvent = new Text(shell, SWT.BORDER);
txtYesEvent.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
txtYesEvent.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent e) {
showKeyboard();
}
#Override
public void focusLost(FocusEvent e) {
closeKeyboard();
}
});
}
protected void closeKeyboard() {
if(kbd != null) {
if(!kbd.isDisposed())
kbd.close();
kbd = null;
}
}
protected void showKeyboard() {
Control ctrlFocus = shell.getDisplay().getFocusControl();
if(!(ctrlFocus instanceof Text))
return;
Text txt = (Text) ctrlFocus;
if(kbd == null && txt.isEnabled() && txt.getEditable()) {
kbd = new Kbd(shell, txt);
kbd.positionRelativeToControl();
kbd.setVisible(true);
Composite parent = txt.getParent();
do {
parent.addControlListener(_parentControlListener);
} while((parent = parent.getParent()) != null);
}
}
private class Kbd extends Shell {
private static final int XMARGIN = 5;
private static final int YMARGIN = 5;
private Display _display;
private Text _txt;
private Point _ptKey;
private Color _clrInfoFG;
private Color _clrInfoBG;
public Kbd(Shell parent, Text associatedCtrl) {
super(parent, SWT.ON_TOP | SWT.NO_TRIM | SWT.TOOL | SWT.NO_FOCUS | SWT.NO_BACKGROUND);
_txt = associatedCtrl;
_display = getDisplay();
_clrInfoFG = _display.getSystemColor(SWT.COLOR_INFO_FOREGROUND);
_clrInfoBG = _display.getSystemColor(SWT.COLOR_INFO_BACKGROUND);
addPaintListener(new PaintListener() {
#Override
public void paintControl(PaintEvent e) {
onPaint(e);
}
});
addMouseListener(new MouseAdapter() {
#Override
public void mouseDown(MouseEvent e) {
if(_txt.isEnabled() && _txt.getEditable()) {
char c = getItemMouseIsOn(e);
if(c != '\0') {
sendKeyEvent(c, SWT.KeyDown);
sendKeyEvent(c, SWT.KeyUp);
}
}
}
});
GC gc = new GC(_display);
_ptKey = new Point(0,0);
for(char c = 'A' ; c <= 'Z' ; c++) {
Point ptChar = gc.textExtent(Character.toString(c));
_ptKey.x = Math.max(_ptKey.x, ptChar.x);
_ptKey.y = Math.max(_ptKey.y, ptChar.y);
}
gc.dispose();
setSize(26 * (_ptKey.x + 2 * XMARGIN), _ptKey.y + 2 * YMARGIN);
}
public void positionRelativeToControl() {
Rectangle rc = _txt.getBounds();
Point ptTxt = new Point(rc.x, rc.y + rc.height);
Point ptNewPosition = _display.map(_txt.getParent(), null, ptTxt);
Point ptCurrentShellPosition = getLocation();
if(!ptNewPosition.equals(ptCurrentShellPosition))
setLocation(ptNewPosition);
}
private void sendKeyEvent(char c, int eventType) {
Event event = new Event();
event.type = eventType;
event.character = c;
_display.post(event);
}
private char getItemMouseIsOn(MouseEvent e) {
Rectangle rc = getClientArea();
if ((rc.x <= e.x) && (e.x <= rc.x + rc.width)) {
int key = e.x / (2 * XMARGIN + _ptKey.x);
if(0 <= key && key <= 25) {
char c = (char) ('A' + key);
return c;
}
}
return '\0';
}
protected void onPaint(PaintEvent e) {
Rectangle rc = getClientArea();
Image img = new Image(_display, rc.width, rc.height);
GC gc = new GC(img);
Color clrFG = gc.getForeground();
Color clrBG = gc.getBackground();
gc.setBackground(_clrInfoBG);
gc.fillRectangle(rc);
gc.setForeground(_clrInfoFG);
int x = rc.x + XMARGIN;
int y = rc.y + YMARGIN;
for(char c = 'A' ; c <= 'Z' ; c++) {
gc.drawText(Character.toString(c), x, y);
x += _ptKey.x + XMARGIN;
gc.drawLine(x, rc.y, x, rc.y + rc.height);
x += XMARGIN;
}
gc.setForeground(clrFG);
gc.setBackground(clrBG);
e.gc.drawImage(img, 0, 0);
gc.dispose();
img.dispose();
}
#Override
protected void checkSubclass() {
}
}
}

Implementing Polyline Connections between Ellipses

I'm trying to create a connection between two ellipses on a canvas, AFTER having created the ellipses and storing their positions on the canvas. These stored positions need to be used to create the connection. The code I've written works for RectangleFigures but does not for Ellipses. I can't seem to see the difference between the two cases. Could someone please help? Thanks.*I've added short testable code to illustrate my problem. To see it working with Rectangles, please uncomment the line saying UNCOMMENT THIS
import java.util.ArrayList;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.ChopboxAnchor;
import org.eclipse.draw2d.Ellipse;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.LightweightSystem;
import org.eclipse.draw2d.PolygonDecoration;
import org.eclipse.draw2d.PolylineConnection;
import org.eclipse.draw2d.RectangleFigure;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.DragSourceListener;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Label;
public class EllipseProblem
{
private Shell shell;
private Display display;
private final Label lblUnicorn;
private final Canvas canvas;
final IFigure panel;
public static ArrayList canvasElements= new ArrayList();
public static void main(String args[])
{
new EllipseProblem();
}
public EllipseProblem()
{
display = new Display();
shell = new Shell(display);
shell.setText("SWT Application");
shell.setLayout(new GridLayout(2, false));
Group grpPalette = new Group(shell, SWT.NONE);
grpPalette.setText("Palette");
grpPalette.setLayout(new GridLayout());
grpPalette.setLayoutData(new GridData(SWT.BEGINNING, SWT.FILL, false, true));
lblUnicorn = new Label(grpPalette, SWT.BORDER | SWT.HORIZONTAL | SWT.CENTER);
lblUnicorn.setText("UNICORN");
lblUnicorn.setAlignment(SWT.CENTER);
final Group grpCanvas = new Group(shell, SWT.NONE);
grpCanvas.setText("Canvas");
grpCanvas.setLayout(new GridLayout());
grpCanvas.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
canvas = new Canvas(grpCanvas, SWT.NONE);
canvas.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
Button btnCreate = new Button(grpPalette, SWT.CENTER);
GridData gd_btnCreate = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_btnCreate.widthHint = 87;
gd_btnCreate.heightHint = 33;
btnCreate.setLayoutData(gd_btnCreate);
btnCreate.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
drawConnection();
}
});
btnCreate.setText("Make Connection");
LightweightSystem lws = new LightweightSystem(canvas);
panel = new Figure();
lws.setContents(panel);
DragSource dragSource1 = new DragSource(lblUnicorn, DND.DROP_COPY);
Transfer[] transfers1 = new Transfer[] { TextTransfer.getInstance() };
dragSource1.setTransfer(transfers1);
dragSource1.addDragListener(new DragSourceListener()
{
public void dragStart(DragSourceEvent event)
{
if (lblUnicorn.getText().length() == 0)
{
event.doit = false;
}
}
public void dragSetData(DragSourceEvent event)
{
if (TextTransfer.getInstance().isSupportedType(event.dataType))
{
event.data = lblUnicorn.getText();
}
}
public void dragFinished(DragSourceEvent event)
{
}
});
Transfer[] types = new Transfer[] { TextTransfer.getInstance() };
DropTarget dropTarget = new DropTarget(canvas, DND.DROP_COPY | DND.DROP_DEFAULT);
dropTarget.setTransfer(types);
dropTarget.addDropListener(new DropTargetListener()
{
public void dragEnter(DropTargetEvent event)
{
if (event.detail == DND.DROP_DEFAULT)
{
if ((event.operations & DND.DROP_COPY) != 0)
{
event.detail = DND.DROP_COPY;
}
else
{
event.detail = DND.DROP_NONE;
}
}
}
public void dragLeave(DropTargetEvent event)
{
}
public void dragOperationChanged(DropTargetEvent event)
{
}
public void dragOver(DropTargetEvent event)
{
}
public void drop(DropTargetEvent event)
{
}
public void dropAccept(final DropTargetEvent event)
{
if (TextTransfer.getInstance().isSupportedType(event.currentDataType))
{
String d = (String) TextTransfer.getInstance().nativeToJava(event.currentDataType);
final String finald= d;
org.eclipse.swt.graphics.Point droppoint = canvas.toControl(event.x, event.y);
canvasElements.add(droppoint);
Rectangle rect=new Rectangle(droppoint.x, droppoint.y, 40, 20);
Rectangle rect2=new Rectangle(droppoint.x+20, droppoint.y, 100, 25);
Ellipse node= new Ellipse();
//RectangleFigure node= new RectangleFigure(); UNCOMMENT THIS
node.setBounds(rect);
System.out.println(node.getBounds());
node.setLocation(new Point(droppoint.x, droppoint.y));
node.setBackgroundColor(ColorConstants.red);
panel.add(node);
org.eclipse.draw2d.Label droppedName=
new org.eclipse.draw2d.Label(finald);
droppedName.setLocation(new Point(droppoint.x, droppoint.y)); //draw2d. point
droppedName.setBounds(rect2);
panel.add(node);
panel.add(droppedName);
canvas.redraw();
}
}
});
shell.pack();
shell.setSize(400, 300);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
}
protected void drawConnection()
{
org.eclipse.swt.graphics.Point swt_origin= (org.eclipse.swt.graphics.Point) canvasElements.get(0);
org.eclipse.draw2d.geometry.Point origin_point= new org.eclipse.draw2d.geometry.Point(swt_origin.x, swt_origin.y);
org.eclipse.swt.graphics.Point swt_destination= (org.eclipse.swt.graphics.Point) canvasElements.get(1);
org.eclipse.draw2d.geometry.Point destination_point= new org.eclipse.draw2d.geometry.Point(swt_destination.x, swt_destination.y);
IFigure origin = panel.findFigureAt(origin_point);
IFigure destination = panel.findFigureAt(destination_point);
PolylineConnection conn = new PolylineConnection();
conn.setSourceAnchor(new ChopboxAnchor(origin));
conn.setTargetAnchor(new ChopboxAnchor(destination));
conn.setTargetDecoration(new PolygonDecoration());
panel.add(conn);
}
}
Your problem is caused by the fact, that your method to determine the source and target IFigures is flawed.
You store the top left corner for the lookup. That works just fine for the RectangleFigure, since that rectangle actually contains the top left corner. The Ellipse, however, doesn't (which is why the source and target of the PolylineConnection is their parent).
Best illustrated with an image:
If you instead store the center of the figure you'll end up with this:

internal frame not working

Hi I have created three frames inside a container and each frame has three buttons which performs the functions of min,max and close. For surprise only one frame is working and the rest three are not working.can you please sort it out.thanks
package Project;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.*;
import java.beans.PropertyVetoException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import javax.swing.plaf.basic.BasicInternalFrameUI;
public class Test4 {
JInternalFrame inf ;
DesktopPane pane;
public static void main(String[] args) {
new Test4();
}
private int xpos = 0;
private int ypos = 0;
public Test4() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exp) {
exp.printStackTrace();
}
pane = new DesktopPane();
pane.add(newInternalFrame());
pane.add(newInternalFrame());
pane.add(newInternalFrame());
JFrame frame = new JFrame();
frame.add(pane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public JInternalFrame newInternalFrame() {
inf= new JInternalFrame("Blah", true, true, true, true);
inf.setLocation(xpos, ypos);
inf.setSize(200, 100);
inf.setVisible(true);
xpos += 50;
ypos += 50;
JPanel jp = new JPanel();
JLabel jl=new JLabel("panel"+xpos);
JButton jb = new JButton("_");
JButton jb2 = new JButton("[]");
JButton jb3 = new JButton("X");
inf.setLayout(new GridLayout(2, 2));
jp.add(jl);
jp.add(jb);
jp.add(jb2);
jp.add(jb3);
inf.add(jp);
jb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
try {
if (inf.getLayer() == JDesktopPane.FRAME_CONTENT_LAYER) {
pane.remove(inf);
pane.add(inf, JDesktopPane.DEFAULT_LAYER);
pane.revalidate();
pane.repaint();
}
inf.pack();
inf.setIcon(true);
} catch (PropertyVetoException ex) {
ex.printStackTrace();
}
}
});
jb2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
try {
if (inf.isMaximum()) {//restore
inf.pack();
} else {//maximize
inf.setMaximum(true);
}
pane.remove(inf);
pane.add(inf, JDesktopPane.FRAME_CONTENT_LAYER);
pane.revalidate();
pane.repaint();
} catch (Exception e) {
e.printStackTrace();
}
}
});
jb3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
try {
inf.dispose();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
BasicInternalFrameTitlePane titlePane = (BasicInternalFrameTitlePane) ((BasicInternalFrameUI) inf.getUI()).getNorthPane();
inf.remove(titlePane);
return inf;
}
public class DesktopPane extends JDesktopPane {
#Override
public void doLayout() {
super.doLayout();
List<Component> icons = new ArrayList<Component>(25);
int maxLayer = 0;
for (Component comp : getComponents()) {
if (comp instanceof JInternalFrame.JDesktopIcon) {
icons.add(comp);
maxLayer = Math.max(getLayer(comp), maxLayer);
}
}
maxLayer++;
int x = 0;
for (Component icon : icons) {
int y = getHeight() - icon.getHeight();
icon.setLocation(x, y);
x += icon.getWidth();
setLayer(icon, maxLayer);
}
}
/* public void doLayout() {
super.doLayout();
List<Component> icons = new ArrayList<Component>(25);
for (Component comp : getComponents()) {
if (comp instanceof JInternalFrame.JDesktopIcon) {
icons.add(comp);
}
}
int x = 0;
for (Component icon : icons) {
int y = getHeight() - icon.getHeight();
icon.setLocation(x, y);
x += icon.getWidth();
}
}*/
}
}
package Project;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.*;
import java.beans.PropertyVetoException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import javax.swing.plaf.basic.BasicInternalFrameUI;
public class Test4 {
private JDesktopPane pane;
public static void main(String[] args) {
new Test4();// there was a little change here
}
private int xpos = 0;
private int ypos = 0;
public Test4() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exp) {
exp.printStackTrace();
}
pane = new Test4.DesktopPane() {
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
};
pane.add(newInternalFrame());
pane.add(newInternalFrame());
pane.add(newInternalFrame());
JFrame frame = new JFrame();
frame.add(pane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public JInternalFrame newInternalFrame() {
final JInternalFrame inf = new JInternalFrame("Blah", true, true, true, true);
inf.setLocation(xpos, ypos);
inf.setSize(200, 100);
inf.setVisible(true);
xpos += 50;
ypos += 50;
JPanel jp = new JPanel();
JLabel jl = new JLabel("panel" + xpos);
JButton jb = new JButton("_");
JButton jb2 = new JButton("[]");
JButton jb3 = new JButton("X");
inf.setLayout(new GridLayout(2, 2));
jp.add(jl);
jp.add(jb);
jp.add(jb2);
jp.add(jb3);
inf.add(jp);
jb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
try {
if (inf.getLayer() == JDesktopPane.FRAME_CONTENT_LAYER) {
pane.remove(inf);
pane.add(inf, JDesktopPane.DEFAULT_LAYER);
pane.revalidate();
pane.repaint();
}
inf.pack();
inf.setIcon(true);
} catch (PropertyVetoException ex) {
ex.printStackTrace();
}
}
});
jb2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
try {
if (inf.isMaximum()) {//restore
inf.pack();
} else {//maximize
inf.setMaximum(true);
}
pane.remove(inf);
pane.add(inf, JDesktopPane.FRAME_CONTENT_LAYER);
pane.revalidate();
pane.repaint();
} catch (Exception e) {
e.printStackTrace();
}
}
});
jb3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
try {
inf.dispose();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
BasicInternalFrameTitlePane titlePane = (BasicInternalFrameTitlePane) ((BasicInternalFrameUI) inf.getUI()).getNorthPane();
inf.remove(titlePane);
return inf;
}
public class DesktopPane extends JDesktopPane {
#Override
public void doLayout() {
super.doLayout();
List<Component> icons = new ArrayList<Component>(25);
int maxLayer = 0;
for (Component comp : getComponents()) {
if (comp instanceof JInternalFrame.JDesktopIcon) {
icons.add(comp);
maxLayer = Math.max(getLayer(comp), maxLayer);
}
}
maxLayer++;
int x = 0;
for (Component icon : icons) {
int y = getHeight() - icon.getHeight();
icon.setLocation(x, y);
x += icon.getWidth();
setLayer(icon, maxLayer);
}
}
}
}
just add the following line
final JInternalFrame inf= new JInternalFrame("Blah", true, true, true, true);
in place of inf= new JInternalFrame("Blah", true, true, true, true);
and remove this JInternalFrame inf from main.

how to add full image in JDialog this dialog is created by JOptionPane

my question is i want to add full background image if JDialog, this JDialog is created by JOptionPane. This image does not cover full Dialog.
If you have any solution please let me know.
public class BrowseFilePath {
public static final String DIALOG_NAME = "what-dialog";
public static final String PANE_NAME = "what-pane";
private static JDialog loginRegister;
private static String path;
private static JPanel Browse_panel = new JPanel(new BorderLayout());
private static JLabel pathLbl = new JLabel("Please Choose Folder / File");
private static JTextField regtxt_file = new JTextField(30);
private static JButton browse_btn = new JButton("Browse");
private static JButton ok_btn = new JButton("Ok");
private static JButton close_btn = new JButton("Cancel");
/*public static void main(String [] arg){
showFileDialog();
}*/
public static void showFileDialog() {
JOptionPane.setDefaultLocale(null);
JOptionPane pane = new JOptionPane(createRegInputComponent());
pane.setName(PANE_NAME);
loginRegister = pane.createDialog("ShareBLU");
/* try {
loginRegister.setContentPane(new JLabel(new ImageIcon(ImageIO.read(AlertWindow.getBgImgFilePath()))));
} catch (IOException e) {
e.printStackTrace();
}*/
loginRegister.setName(DIALOG_NAME);
loginRegister.setSize(380,150);
loginRegister.setVisible(true);
if(pane.getInputValue().equals("Ok")){
String getTxt = regtxt_file.getText();
BrowseFilePath.setPath(getTxt);
}
else if(pane.getInputValue().equals("Cancel")){
regtxt_file.setText("");
System.out.println("Pressed Cancel Button =======********=");
System.exit(0);
}
}
public static String getPath() {
return path;
}
public static void setPath(String path) {
BrowseFilePath.path = path;
}
private static JComponent createRegInputComponent() {
Browse_panel = new JBackgroundPanel();
Browse_panel.setLayout(new BorderLayout());
Box rows = Box.createVerticalBox();
Browse_panel.setBounds(0,0,380,150);
Browse_panel.add(pathLbl);
pathLbl.setForeground(Color.white);
pathLbl.setBounds(20, 20, 200, 20);
Browse_panel.add(regtxt_file);
regtxt_file.setToolTipText("Select File/Folder..");
regtxt_file.setBounds(20, 40, 220, 20);
Browse_panel.add(browse_btn);
browse_btn.setToolTipText("Browse");
browse_btn.setBounds(250, 40, 90, 20);
Browse_panel.add(ok_btn);
ok_btn.setToolTipText("Ok");
ok_btn.setBounds(40, 75, 80, 20);
Browse_panel.add(close_btn);
close_btn.setToolTipText("Cancel");
close_btn.setBounds(130, 75, 80, 20);
ActionListener chooseMe = createChoiceAction();
ok_btn.addActionListener(chooseMe);
close_btn.addActionListener(chooseMe);
browse_btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int selection = JFileChooser.FILES_AND_DIRECTORIES;
fileChooser.setFileSelectionMode(selection);
fileChooser.setAcceptAllFileFilterUsed(false);
int rVal = fileChooser.showOpenDialog(null);
if (rVal == JFileChooser.APPROVE_OPTION) {
path = fileChooser.getSelectedFile().toString();
regtxt_file.setText(path);
}
}
});
rows.add(Box.createVerticalStrut(105));
Browse_panel.add(rows,BorderLayout.CENTER);
return Browse_panel;
}
public static ActionListener createChoiceAction() {
ActionListener chooseMe = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton choice = (JButton) e.getSource();
// find the pane so we can set the choice.
Container parent = choice.getParent();
while (!PANE_NAME.equals(parent.getName())) {
parent = parent.getParent();
}
JOptionPane pane = (JOptionPane) parent;
pane.setInputValue(choice.getText());
// find the dialog so we can close it.
while ((parent != null) && !DIALOG_NAME.equals(parent.getName()))
{
parent = parent.getParent();
//parent.setBounds(0, 0, 350, 150);
}
if (parent != null) {
parent.setVisible(false);
}
}
};
return chooseMe;
}
}
Don't use JOptionPane but use a full-blown JDialog. Set the content pane to a JComponent that overrides paintComponent() and returns an appropriate getPreferredSize().
Example code below:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestBackgroundImage {
private static final String BACKHGROUND_IMAGE_URL = "http://cache2.allpostersimages.com/p/LRG/27/2740/AEPND00Z/affiches/blue-fiber-optic-wires-against-black-background.jpg";
protected void initUI() throws MalformedURLException {
JDialog dialog = new JDialog((Frame) null, TestBackgroundImage.class.getSimpleName());
dialog.setModal(true);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
final ImageIcon backgroundImage = new ImageIcon(new URL(BACKHGROUND_IMAGE_URL));
JPanel mainPanel = new JPanel(new BorderLayout()) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage.getImage(), 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width = Math.max(backgroundImage.getIconWidth(), size.width);
size.height = Math.max(backgroundImage.getIconHeight(), size.height);
return size;
}
};
mainPanel.add(new JButton("A button"), BorderLayout.WEST);
dialog.add(mainPanel);
dialog.setSize(400, 300);
dialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestBackgroundImage().initUI();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Don't forget to provide an appropriate parent Frame

how to drag and drop files from a directory in java

I want to implement dragging and dropping of files from a directory such as someones hard drive but can't figure out how to do it. I've read the java api but it talks of color pickers and dragging and dropping between lists but how to drag files from a computers file system and drop into my application. I tried writing the transferhandler class and a mouse event for when the drag starts but nothing seems to work. Now I'm back to just having my JFileChooser set so drag has been enabled but how to drop?
Any info or point in the right direction greatly appreciated.
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
public class FileChooserDemo
extends JPanel
implements ActionListener
{
JLabel selectedFileLabel;
JList selectedFilesList;
JLabel returnCodeLabel;
public FileChooserDemo()
{
super();
createContent();
}
void initFrameContent()
{
JPanel closePanel = new JPanel();
add(closePanel, BorderLayout.SOUTH);
}
private void createContent()
{
setLayout(new BorderLayout());
JPanel NorthPanel = new JPanel();
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
JMenuItem quit = new JMenuItem("Quit");
menuBar.add(menu);
menu.add(quit);
NorthPanel.add(menu,BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new GridLayout(7,1 ));
JButton openButton = new JButton("Open...");
openButton.setActionCommand("OPEN");
openButton.addActionListener(this);
buttonPanel.add(openButton);
JButton saveButton = new JButton("Save...");
saveButton.setActionCommand("SAVE");
saveButton.addActionListener(this);
buttonPanel.add(saveButton);
JButton delete = new JButton("Delete");
delete.addActionListener(this);
delete.setActionCommand("DELETE");
buttonPanel.add(delete);
add(buttonPanel, BorderLayout.WEST);
// create a panel to display the selected file(s) and the return code
JPanel displayPanel = new JPanel(new BorderLayout());
selectedFileLabel = new JLabel("-");
selectedFileLabel.setBorder(BorderFactory.createTitledBorder
("Selected File/Directory "));
displayPanel.add(selectedFileLabel, BorderLayout.NORTH);
selectedFilesList = new JList();
JScrollPane sp = new JScrollPane(selectedFilesList);
sp.setBorder(BorderFactory.createTitledBorder("Selected Files "));
MouseListener listener = new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
JComponent comp = (JComponent) me.getSource();
TransferHandler handler = comp.getTransferHandler();
handler.exportAsDrag(comp, me, TransferHandler.MOVE);
}
};
selectedFilesList.addMouseListener(listener);
displayPanel.add(sp);
returnCodeLabel = new JLabel("");
returnCodeLabel.setBorder(BorderFactory.createTitledBorder("Return Code"));
displayPanel.add(returnCodeLabel, BorderLayout.SOUTH);
add(displayPanel);
}
public void actionPerformed(ActionEvent e)
{
int option = 0;
File selectedFile = null;
File[] selectedFiles = new File[0];
if (e.getActionCommand().equals("CLOSE"))
{
System.exit(0);
}
else if (e.getActionCommand().equals("OPEN"))
{
JFileChooser chooser = new JFileChooser();
chooser.setDragEnabled(true);
chooser.setMultiSelectionEnabled(true);
option = chooser.showOpenDialog(this);
selectedFiles = chooser.getSelectedFiles();
}
else if (e.getActionCommand().equals("SAVE"))
{
JFileChooser chooser = new JFileChooser();
option = chooser.showSaveDialog(this);
selectedFiles = chooser.getSelectedFiles();
}
// display the selection and return code
if (selectedFile != null)
selectedFileLabel.setText(selectedFile.toString());
else
selectedFileLabel.setText("null");
DefaultListModel listModel = new DefaultListModel();
for (int i =0; i < selectedFiles.length; i++)
listModel.addElement(selectedFiles[i]);
selectedFilesList.setModel(listModel);
returnCodeLabel.setText(Integer.toString(option));
}
public static void main(String[] args)
{
SwingUtilities.invokeLater
(new Runnable()
{
public void run()
{
FileChooserDemo app = new FileChooserDemo();
app.initFrameContent();
JFrame frame = new JFrame("LoquetUP");
frame.getContentPane().add(app);
frame.setDefaultCloseOperation(3);
frame.setSize(600,400);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
//frame.pack();
frame.setVisible(true);
}
});
}
}
This is my take on the idea. I've used the "traditional" drag and drop API in this example. It has some extra "paint" tweaks just to show off what you might be able to do.
This example doesn't scan folders dropped onto it, so any folder will only register as a single file, but I'm sure you can work it out
public class TestDragNDropFiles {
public static void main(String[] args) {
new TestDragNDropFiles();
}
public TestDragNDropFiles() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new DropPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DropPane extends JPanel {
private DropTarget dropTarget;
private DropTargetHandler dropTargetHandler;
private Point dragPoint;
private boolean dragOver = false;
private BufferedImage target;
private JLabel message;
public DropPane() {
try {
target = ImageIO.read(new File("target.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
setLayout(new GridBagLayout());
message = new JLabel();
message.setFont(message.getFont().deriveFont(Font.BOLD, 24));
add(message);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
protected DropTarget getMyDropTarget() {
if (dropTarget == null) {
dropTarget = new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, null);
}
return dropTarget;
}
protected DropTargetHandler getDropTargetHandler() {
if (dropTargetHandler == null) {
dropTargetHandler = new DropTargetHandler();
}
return dropTargetHandler;
}
#Override
public void addNotify() {
super.addNotify();
try {
getMyDropTarget().addDropTargetListener(getDropTargetHandler());
} catch (TooManyListenersException ex) {
ex.printStackTrace();
}
}
#Override
public void removeNotify() {
super.removeNotify();
getMyDropTarget().removeDropTargetListener(getDropTargetHandler());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (dragOver) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(new Color(0, 255, 0, 64));
g2d.fill(new Rectangle(getWidth(), getHeight()));
if (dragPoint != null && target != null) {
int x = dragPoint.x - 12;
int y = dragPoint.y - 12;
g2d.drawImage(target, x, y, this);
}
g2d.dispose();
}
}
protected void importFiles(final List files) {
Runnable run = new Runnable() {
#Override
public void run() {
message.setText("You dropped " + files.size() + " files");
}
};
SwingUtilities.invokeLater(run);
}
protected class DropTargetHandler implements DropTargetListener {
protected void processDrag(DropTargetDragEvent dtde) {
if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dtde.acceptDrag(DnDConstants.ACTION_COPY);
} else {
dtde.rejectDrag();
}
}
#Override
public void dragEnter(DropTargetDragEvent dtde) {
processDrag(dtde);
SwingUtilities.invokeLater(new DragUpdate(true, dtde.getLocation()));
repaint();
}
#Override
public void dragOver(DropTargetDragEvent dtde) {
processDrag(dtde);
SwingUtilities.invokeLater(new DragUpdate(true, dtde.getLocation()));
repaint();
}
#Override
public void dropActionChanged(DropTargetDragEvent dtde) {
}
#Override
public void dragExit(DropTargetEvent dte) {
SwingUtilities.invokeLater(new DragUpdate(false, null));
repaint();
}
#Override
public void drop(DropTargetDropEvent dtde) {
SwingUtilities.invokeLater(new DragUpdate(false, null));
Transferable transferable = dtde.getTransferable();
if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dtde.acceptDrop(dtde.getDropAction());
try {
List transferData = (List) transferable.getTransferData(DataFlavor.javaFileListFlavor);
if (transferData != null && transferData.size() > 0) {
importFiles(transferData);
dtde.dropComplete(true);
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
dtde.rejectDrop();
}
}
}
public class DragUpdate implements Runnable {
private boolean dragOver;
private Point dragPoint;
public DragUpdate(boolean dragOver, Point dragPoint) {
this.dragOver = dragOver;
this.dragPoint = dragPoint;
}
#Override
public void run() {
DropPane.this.dragOver = dragOver;
DropPane.this.dragPoint = dragPoint;
DropPane.this.repaint();
}
}
}
}
You need to experiment with Drag & Drop and see exactly what flavors are available when you try to drag files. If you do this in your custom TransferHandler you'll be pleasantly surprised one Flavor is the DataFlavor.javaFileListFlavor, which indicates that the item can be used simply as a List. Try it and you'll see that it works!
Note on review of your posted code, I don't see any code for your attempt at using a TransferHandler, so it is hard to say what you could be doing wrong here.
Edit 1
You seem to be trying to use a MouseListener for your drag and drop, and I'm not familiar with this usage. Can you show a reference to a tutorial that tells you to do this?
Edit 2
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class FileDragDemo extends JPanel {
private JList list = new JList();
public FileDragDemo() {
list.setDragEnabled(true);
list.setTransferHandler(new FileListTransferHandler(list));
add(new JScrollPane(list));
}
private static void createAndShowGui() {
FileDragDemo mainPanel = new FileDragDemo();
JFrame frame = new JFrame("FileDragDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class FileListTransferHandler extends TransferHandler {
private JList list;
public FileListTransferHandler(JList list) {
this.list = list;
}
public int getSourceActions(JComponent c) {
return COPY_OR_MOVE;
}
public boolean canImport(TransferSupport ts) {
return ts.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
}
public boolean importData(TransferSupport ts) {
try {
#SuppressWarnings("rawtypes")
List data = (List) ts.getTransferable().getTransferData(
DataFlavor.javaFileListFlavor);
if (data.size() < 1) {
return false;
}
DefaultListModel listModel = new DefaultListModel();
for (Object item : data) {
File file = (File) item;
listModel.addElement(file);
}
list.setModel(listModel);
return true;
} catch (UnsupportedFlavorException e) {
return false;
} catch (IOException e) {
return false;
}
}
}

Categories