forum.test17
forum.test17

Reputation: 2219

How to have custom drag and drop support in Java Swing

I have enabled the default custom drag and support for a JTree, it works like a charm :)

I have one tree, one text and one editor pane, if I drag any node from the tree to the text area, it pastes the text, but when I do the same thing to the editor pane, it doesn't copy the plain text, it copies the text with bullet and changes the entire layout.

All I need is to copy the plain text to the editor pane, this only happens when I set the content type to "plain/text" when the change the content type it will copy with bullet symbol...

Is there any possibility that when I drop to the text area/editor pane, instead of name of node, it should place 'name of the node +"?"', I have googled it but only can find how to enable the drag and support for JLabel.

package testing_dragging;

import java.awt.datatransfer.DataFlavor;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComponent;
import javax.swing.TransferHandler;


public class test_dragging_form extends javax.swing.JFrame {

/**
 * Creates new form test_dragging_form
 */
public test_dragging_form() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();
    jTree1 = new javax.swing.JTree();
    jScrollPane2 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jScrollPane3 = new javax.swing.JScrollPane();
    jEditorPane1 = new javax.swing.JEditorPane();
    jLabel1 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jTree1.setDragEnabled(true);
    jTree1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
        public void mouseMoved(java.awt.event.MouseEvent evt) {
            jTree1MouseMoved(evt);
        }
    });
    jScrollPane1.setViewportView(jTree1);

    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jTextArea1.setDragEnabled(true);
    jScrollPane2.setViewportView(jTextArea1);

    try
    {
        jEditorPane1.setPage("file:///home/rocky/Desktop/test_plan_template.html");
    }
    catch(Exception ex)
    {
        System.out.println("Some exception occured"+ ex.getMessage());
    }
    jEditorPane1.setDragEnabled(true);
    jScrollPane3.setViewportView(jEditorPane1);

    jLabel1.setText("draglabel");
    jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mousePressed(java.awt.event.MouseEvent evt) {
            jLabel1MousePressed(evt);
        }
    });

    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(29, 29, 29)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(55, 55, 55)
                    .addComponent(jLabel1))
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap(99, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addGap(0, 12, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(47, 47, 47)
                            .addComponent(jLabel1)))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 200, javax.swing.GroupLayout.PREFERRED_SIZE))))
    );

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

private void jTree1MouseMoved(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:
    JComponent comp = (JComponent)evt.getSource();
    TransferHandler handler = comp.getTransferHandler();


    comp.setTransferHandler(handler);

    handler.exportAsDrag(comp, evt, TransferHandler.COPY);
}

private void jLabel1MousePressed(java.awt.event.MouseEvent evt) {
    // TODO add your handling code here:
    JComponent comp = (JComponent)evt.getSource();
    TransferHandler handler = new TransferHandler("text");

    comp.setTransferHandler(handler);
    handler.exportAsDrag(comp, evt, TransferHandler.COPY);
}

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /*
     * Set the Nimbus look and feel
     */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /*
     * If Nimbus (introduced in Java SE 6) is not available, stay with the
     * default look and feel. For details see
     * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(test_dragging_form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(test_dragging_form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(test_dragging_form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(test_dragging_form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /*
     * Create and display the form
     */
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new test_dragging_form().setVisible(true);
        }
    });
}
// Variables declaration - do not modify
private javax.swing.JEditorPane jEditorPane1;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTree jTree1;
// End of variables declaration
}

Upvotes: 2

Views: 1233

Answers (1)

yggdraa
yggdraa

Reputation: 2050

I have a little experience with custom drag'n'drop and may be your problem has better solution, but this works:

Make your custom dropTarget for JEditorPane. It will pick the text/plain DataFlavor instead of default text/html one;

class JEditorPaneDropTarget extends DropTargetAdapter{

    JEditorPaneDropTarget(JEditorPane pane) {
        new DropTarget(pane, this);
    }

    @Override
    public void drop(DropTargetDropEvent dtde) {
        Transferable tr = dtde.getTransferable();
        Object data;
        try {
            DataFlavor df = new DataFlavor("text/plain; class=java.lang.String");
            data = tr.getTransferData(df);
            JEditorPane pane = (JEditorPane) ((DropTarget)dtde.getSource()).getComponent();
            pane.setText((String)data);
        } catch (Exception e) {
            //
        }
    }
}

Initialize it with your jEditorPane1 somewhere in initComponents():

new JEditorPaneDropTarget(jEditorPane1); 

Here are no checks for possible null or cast exceptions, so you will need those too. Read something about DataFlavors and how to use them. May be there is a way to mention right DataFlavor to use without writing whole custom DropTarget class, but i didn't find any.

Upvotes: 1

Related Questions