如何在Java Swing中使用自定义拖放支持

时间:2012-01-23 11:13:02

标签: java swing java-ee netbeans mouseevent

我已启用JTree的默认自定义拖动和支持,它就像一个魅力:)

我有一个树,一个文本和一个编辑器窗格,如果我将任何节点从树拖到文本区域,它会粘贴文本,但是当我对编辑器窗格执行相同操作时,它不会复制纯文本,它用子弹复制文本并更改整个布局。

我需要的只是将纯文本复制到编辑器窗格,这只有在我将内容类型设置为“plain / text”时才会发生,当更改内容类型时,它将使用项目符号复制...

当我放入文本区域/编辑器窗格而不是节点名称时,是否应该放置'节点名称+“?”',我已经用Google搜索了它,但只能找到如何启用它拖动和支持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
}

1 个答案:

答案 0 :(得分:1)

我对自定义拖放有一点经验,可能是你的问题有更好的解决方案,但这有效:

为JEditorPane制作自定义dropTarget。它将选择text / plain DataFlavor而不是默认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) {
            //
        }
    }
}

在initComponents()的某处使用jEditorPane1初始化它:

new JEditorPaneDropTarget(jEditorPane1); 

这里没有检查可能的null或强制转换异常,所以你也需要这些。 阅读有关DataFlavors以及如何使用它们的内容。可能有一种方法可以提到使用正确的DataFlavor而无需编写完整的自定义DropTarget类,但我没有找到任何。