This program demonstrates drag and drop in an image list. : Drag Drop « Swing JFC « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JDK 6
25.JNDI LDAP
26.JPA
27.JSP
28.JSTL
29.Language Basics
30.Network Protocol
31.PDF RTF
32.Reflection
33.Regular Expressions
34.Scripting
35.Security
36.Servlets
37.Spring
38.Swing Components
39.Swing JFC
40.SWT JFace Eclipse
41.Threads
42.Tiny Application
43.Velocity
44.Web Services SOA
45.XML
Java Tutorial
Java Book
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
SCJP
Java » Swing JFC » Drag DropScreenshots 
This program demonstrates drag and drop in an image list.
 
/*
 This program is a part of the companion code for Core Java 8th ed.
 (http://horstmann.com/corejava)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.DropMode;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.TransferHandler;

/**
 * This program demonstrates drag and drop in an image list.
 
 @version 1.00 2007-09-20
 @author Cay Horstmann
 */
public class ImageListDnDTest {
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      public void run() {
        JFrame frame = new ImageListDnDFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
      }
    });
  }
}

class ImageListDnDFrame extends JFrame {
  public ImageListDnDFrame() {
    setTitle("ImageListDnDTest");
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    list1 = new ImageList(new File("images1").listFiles());
    list2 = new ImageList(new File("images2").listFiles());
    setLayout(new GridLayout(21));
    add(new JScrollPane(list1));
    add(new JScrollPane(list2));
  }

  private ImageList list1;

  private ImageList list2;

  private static final int DEFAULT_WIDTH = 600;

  private static final int DEFAULT_HEIGHT = 500;
}

class ImageList extends JList {
  public ImageList(File[] imageFiles) {
    DefaultListModel model = new DefaultListModel();
    for (File f : imageFiles)
      model.addElement(new ImageIcon(f.getPath()));

    setModel(model);
    setVisibleRowCount(0);
    setLayoutOrientation(JList.HORIZONTAL_WRAP);
    setDragEnabled(true);
    setDropMode(DropMode.ON_OR_INSERT);
    setTransferHandler(new ImageListTransferHandler());
  }
}

class ImageListTransferHandler extends TransferHandler {
  // Support for drag

  public int getSourceActions(JComponent source) {
    return COPY_OR_MOVE;
  }

  protected Transferable createTransferable(JComponent source) {
    JList list = (JListsource;
    int index = list.getSelectedIndex();
    if (index < 0)
      return null;
    ImageIcon icon = (ImageIconlist.getModel().getElementAt(index);
    return new ImageTransferable(icon.getImage());
  }

  protected void exportDone(JComponent source, Transferable data, int action) {
    if (action == MOVE) {
      JList list = (JListsource;
      int index = list.getSelectedIndex();
      if (index < 0)
        return;
      DefaultListModel model = (DefaultListModellist.getModel();
      model.remove(index);
    }
  }

  // Support for drop

  public boolean canImport(TransferSupport support) {
    if (support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
      if (support.getUserDropAction() == MOVE)
        support.setDropAction(COPY);
      return true;
    else
      return support.isDataFlavorSupported(DataFlavor.imageFlavor);
  }

  public boolean importData(TransferSupport support) {
    JList list = (JListsupport.getComponent();
    DefaultListModel model = (DefaultListModellist.getModel();

    Transferable transferable = support.getTransferable();
    List<DataFlavor> flavors = Arrays.asList(transferable.getTransferDataFlavors());

    List<Image> images = new ArrayList<Image>();

    try {
      if (flavors.contains(DataFlavor.javaFileListFlavor)) {
        List<File> fileList = (List<File>transferable
            .getTransferData(DataFlavor.javaFileListFlavor);
        for (File f : fileList) {
          try {
            images.add(ImageIO.read(f));
          catch (IOException ex) {
            // couldn't read image--skip
          }
        }
      else if (flavors.contains(DataFlavor.imageFlavor)) {
        images.add((Imagetransferable.getTransferData(DataFlavor.imageFlavor));
      }

      int index;
      if (support.isDrop()) {
        JList.DropLocation location = (JList.DropLocationsupport.getDropLocation();
        index = location.getIndex();
        if (!location.isInsert())
          model.remove(index)// replace location
      else
        index = model.size();
      for (Image image : images) {
        model.add(index, new ImageIcon(image));
        index++;
      }
      return true;
    catch (IOException ex) {
      return false;
    catch (UnsupportedFlavorException ex) {
      return false;
    }
  }
}

/*
 * This program is a part of the companion code for Core Java 8th ed.
 * (http://horstmann.com/corejava)
 
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * This class is a wrapper for the data transfer of image objects.
 */
class ImageTransferable implements Transferable {
  /**
   * Constructs the selection.
   
   @param image
   *          an image
   */
  public ImageTransferable(Image image) {
    theImage = image;
  }

  public DataFlavor[] getTransferDataFlavors() {
    return new DataFlavor[] { DataFlavor.imageFlavor };
  }

  public boolean isDataFlavorSupported(DataFlavor flavor) {
    return flavor.equals(DataFlavor.imageFlavor);
  }

  public Object getTransferData(DataFlavor flavorthrows UnsupportedFlavorException {
    if (flavor.equals(DataFlavor.imageFlavor)) {
      return theImage;
    else {
      throw new UnsupportedFlavorException(flavor);
    }
  }

  private Image theImage;
}

   
  
Related examples in the same category
1.Tree: Drag and DropTree: Drag and Drop
2.Drag and dropDrag and drop
3.Adding Image-Dragging Behavior
4.Dropper - show File Drop Target from Drag-n-DropDropper - show File Drop Target from Drag-n-Drop
5.Demonstrate various aspects of Swing data transferDemonstrate various aspects of Swing data transfer
6.File Tree Drop TargetFile Tree Drop Target
7.File Tree Drag SourceFile Tree Drag Source
8.Editor Drop Target 4Editor Drop Target 4
9.Drag Drop Tree ExampleDrag Drop Tree Example
10.JLabel Drag Source JLabel Drag Source
11.Panel Drop TargetPanel Drop Target
12.Editor Drop Target 3Editor Drop Target 3
13.Editor Drop TargetEditor Drop Target
14.Editor Drop Target 2Editor Drop Target 2
15.JTextArea subclass allows TransferableColor objects toJTextArea subclass allows TransferableColor objects to
16.Transferable Color
17.Color Drag Source
18.A sample component for dragging and dropping a collection of files into a tree.A sample component for dragging and dropping a collection of files into a tree.
19.Test of the DragGesture classes and JList to see if weTest of the DragGesture classes and JList to see if we
20.A TransferHandler and JTextArea that will accept any drop at allA TransferHandler and JTextArea that will accept any drop at all
21.Drag and drop: TextAreaDrag and drop: TextArea
22.Drag capabilities: JListDrag capabilities: JList
23.A simple drop tester application for JDK 1.4 Swing componentsA simple drop tester application for JDK 1.4 Swing components
24.Drag and Drop:JList and ListDrag and Drop:JList and List
25.DnD (drag and drop)JTree code DnD (drag and drop)JTree code
26.Drop: TextAreaDrop: TextArea
27.Drag and drop: TextArea 2Drag and drop: TextArea 2
28.Label DnD (Drag and Drop) Label DnD (Drag and Drop)
29.LabelDnD2 allows dropping color onto the foreground of the JLabelLabelDnD2 allows dropping color onto the foreground of the JLabel
30.Drag List Demo Drag List Demo
31.Drag Picture Demo
32.Extended DnD (Drag and Drop) DemoExtended DnD (Drag and Drop) Demo
33.Drag Color DemoDrag Color Demo
34.Drag File DemoDrag File Demo
35.Drag Picture Demo 2
36.Drag Color TextField DemoDrag Color TextField Demo
37.BasicDnD (Drag and Drop)BasicDnD (Drag and Drop)
38.Drag and drop icons: use an icon property.
39.Implement drag & drop functionality in your application
40.Detect a drag initiating gesture in your application
41.Making a Component Draggable
42.Getting and Setting Text on the System Clipboard
43.Use drag and drop to reorder a list
44.Create a drag source a drop target and a transferable object.
45.implements DragGestureListener, Transferable
46.Comma separated text will be inserted into two or more rows.
47.TransferHandler subclass wraps another TransferHandler and delegates most of its operations to the wrapped handler
48.Setting text drag in a JTextArea
49.Built-in drag and drop support: utilize a TransferHandler class
50.This program demonstrates the basic Swing support for drag and drop.
w___w__w___.___j___ava_2_s_.___c__om_ | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.