Swing - SPLessons

Swing Drag and Drop

Chapter 17

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Swing Drag and Drop

Swing Drag and Drop

shape Description

Drag and Drop will have the functionality that can make the complex things as easy.For example to insert the rectangle box into the frame user needs to perform copy and paste operation then it takes more time, With the help of Swing Drag and Drop concept it easy to insert.

Some software languages also will use the functionality of Swing Drag and Drop such as Dot Net. In swing to make the frame more effective Drag and Drop is the key component. In Swing almost all the components will have the Drag and Drop functionality, here developer needs to use TransferHandler to pass the data between the components. The following example describes the use of Swing Drag and Drop.

Drag and Drop

shape Example

The source code of Swing Drag and Drop has been explained as follows.

DragandDrop.java

package swing;//created a package as swing

import javax.swing.JButton;//import all the required packages
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.TransferHandler;


public class DragandDrop extends JFrame {//created a class as DragandDrop that should extend JFrame

    JTextField field;//creating a text field
    JButton button;//creating a button 

    public DragandDrop() {

        setTitle("Drag & Drop");//created title

        setLayout(null);

        button = new JButton("Button");//created a button
        button.setBounds(200, 50, 90, 25);//setting sizes to the button.

        field = new JTextField();//creatd a textfield
        field.setBounds(30, 50, 150, 25);//setting sizes to the text field

        add(button);//button added
        add(field);//text added

        field.setDragEnabled(true);//enabling dragging support to the text field.
        button.setTransferHandler(new TransferHandler("text"));//created a class TransferHandler that can send the data between the components.

        setSize(330, 150);//creating window size.
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//to close the window.
        setLocationRelativeTo(null);//set the window location on the screen.
        setVisible(true);//to visible the window
    }

    public static void main(String[] args) {//created main method.
        new DragandDrop();
    }
}

Where text field has a built in support to dragging so enable field.setDragEnabled(true);.

field.setDragEnabled(true);

Implement TransferHandler to transfer the data between the components.

button.setTransferHandler(new TransferHandler("text"));

Output:

If the above code executed successfully,output will be as follows .

In the above output one text field and button are inserted, where user can insert the text and drop that text in button place by dragging the text as follows.

DropingList

shape Example

The source code of an application is as follows.

DropingList.java

package swing;//Created a package with the name swing

import java.awt.Dimension;//import all the required packages
import java.awt.FlowLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import javax.swing.DefaultListModel;
import javax.swing.DropMode;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.TransferHandler;


public class DropingList extends JFrame {//created a class with the name DropingList that should extend JFrame

    JTextField field;//created text field
    DefaultListModel model;//Default model will be created

    public DropingList() {

        setTitle("DropingList");//set the title as DropingList

        JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 15, 15));//creating a panel

        JScrollPane pane = new JScrollPane();
        pane.setPreferredSize(new Dimension(180, 150));//setting the size

        model = new DefaultListModel();
        JList list = new JList(model);

        list.setDropMode(DropMode.INSERT);
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.setTransferHandler(new ListHandler());

        field = new JTextField("");//to write new text
        field.setPreferredSize(new Dimension(150, 25));//creating sizes
        field.setDragEnabled(true);//to enable the dragging 

        panel.add(field);
        pane.getViewport().add(list); 
        panel.add(pane);

        add(panel);

        pack();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//to close the window
        setLocationRelativeTo(null);//to set the window in center position of the screen
        setVisible(true);//to visible the window
    }


    private class ListHandler extends TransferHandler {//created a class ListHandler that should extend TransferHandler ,to transfer the data between the componnents
        public boolean canImport(TransferSupport support) {
             if (!support.isDrop()) {
                 return false;
             }

             return support.isDataFlavorSupported(DataFlavor.stringFlavor);
         }

         public boolean importData(TransferSupport support) {
             if (!canImport(support)) {
               return false;
             }

             Transferable transferable = support.getTransferable();
             String line;
             try {
               line = (String) transferable.getTransferData(DataFlavor.stringFlavor);
             } catch (Exception e) {
               return false;
             }

             JList.DropLocation dl = (JList.DropLocation) support.getDropLocation();
             int index = dl.getIndex();

             String[] data = line.split(",");
             for (String item: data) {
                 if (!item.isEmpty())
                    model.add(index++, item.trim());
             }
             return true;
         }
    }

    public static void main(String[] args) {//writing main method here
        new DropingList();
    }
}

To insert elements into the list component enable the DropMode.INSERT .

list.setDropMode(DropMode.INSERT);

Write the transfer handler method to transfer the data between the components.

list.setTransferHandler(new ListHandler());

Provide the dragging feature to the text field component.

field.setDragEnabled(true);

Permit only string operation,if method is false then drop function will be cancelled.

public boolean canImport(TransferSupport support) {
    if (!support.isDrop()) {
        return false;
    }
    return support.isDataFlavorSupported(DataFlavor.stringFlavor);
}

Write the importData()method to fetch the information from drag & drop operation to the location.

public boolean importData(TransferSupport support) {
...
}

Divide the text data and insert in rows.

String[] data = line.split(",");
for (String item: data) {
    if (!item.isEmpty())
        model.add(index++, item.trim());
}

Output:

If above code executed successfully,output will be as follows.

In the above drop list window, user can write the text messages and drag them into another text field as follows.

Summary

shape Key Points

  • Swing Drag and Drop – JDK 1.2 version introduced drag and drop functionality to pass the data between the components.
  • Swing Drag and Drop – Drag and drop will be available in java.awt.dnd package.
  • Swing Drag and Drop – TransferHandler used to pass the data between the components.