Java JList => Drag Drop Images and Show.

May 8, 2017 Oclemy Java JList, Java DragDrop 3 minutes, 7 seconds

Quick Intro

  • Hey,lets try something cool.
  • Drag images from our machine to our Jlist.
  • Capture the images and dynamically add them in our Jlist component.
  • We shall need the help of DragListener and DropTarget classes.
  • Lets check below.

Demo

Java Jlist DragDrop Images

Source Code Reference    

package DragList;

import java.awt.dnd.DropTarget;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

public class DragListMain extends javax.swing.JFrame {

    public DragListMain() {
        initComponents();

      connectToDragDrop();
    }

    private void connectToDragDrop()
    {
        DragListener d=new DragListener(jList1);

         //SET TARGET TO JFRAME
        new DropTarget(this,d);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(45, 155, 193));

        jList1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jList1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jList1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 303, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(18, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 426, Short.MAX_VALUE)
                .addContainerGap())
        );

        jLabel2.setText("ProgrammingWizards Channel");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(161, 161, 161)
                .addComponent(jLabel2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(57, 57, 57)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(54, 237, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addGap(3, 3, 3)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(40, 40, 40))
        );

        pack();
    }// </editor-fold>

    private void jList1MouseClicked(java.awt.event.MouseEvent evt) {
      JOptionPane.showMessageDialog(null, jList1.getSelectedValue().toString());
    }

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
//                 try {
//                    // select Look and Feel
//                    UIManager.setLookAndFeel("com.jtattoo.plaf.smart.SmartLookAndFeel");
//            // start application
//
//                } catch (Exception ex) {
//                    ex.printStackTrace();
//                }
                new DragListMain().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel2;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration
}

/***************************************************************/

package DragList;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.File;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JList;
import javax.swing.JOptionPane;

public class DragListener implements DropTargetListener  {

    //MODEL
    DefaultListModel dm=new DefaultListModel();

    JList list=new JList();

    public DragListener(JList list)
    {
        this.list=list;
    }

    @Override
    public void dragEnter(DropTargetDragEvent dtde) {

    }

    @Override
    public void dragOver(DropTargetDragEvent dtde) {
    }

    @Override
    public void dropActionChanged(DropTargetDragEvent dtde) {
    }

    @Override
    public void dragExit(DropTargetEvent dte) {
    }

    @Override
    public void drop(DropTargetDropEvent ev) {

        //ACCESPT DROPPED ITEMS
        ev.acceptDrop(DnDConstants.ACTION_COPY);
         //GET DROPPED ITEMS
        Transferable t=ev.getTransferable();

        //GET DATA FORMATS OF THE ITEMS
        DataFlavor[] df=t.getTransferDataFlavors();

        //LOOP THRU FLAVORS
        for(DataFlavor f: df)
        {
            try
            {
                //CHECK IF ITEMS ARE FILE TYPE
                if(f.isFlavorJavaFileListType())
                {
                    //GET LIST OF THEM
                    List<File> files=(List<File>) t.getTransferData(f);

                    //LOOP THRU THEM
                    for(File file: files)
                    {
                        String path=file.getPath();
                        addImage(path);
                    }

                }

            }catch (Exception ex) {
                JOptionPane.showMessageDialog(null, ex);
            }
        }

    }

    //ADD IMAGES
    private void addImage(String path)
    {
        //ICON
        ImageIcon icon=new ImageIcon(path);

        dm.addElement(icon);

        list.setModel(dm);
    }

}

Best Regards.

Comments