简体   繁体   English

如何在Java Swing中具有自定义拖放支持

[英]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 :) 我已经启用了默认的自定义拖动和对JTree支持,它的工作原理很像:)

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 . 当我放到文本区域/编辑器窗格时,是否有可能代替“节点名称”,而应放置“节点名称+“?””,我已经在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
}

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. 为JEditorPane设置自定义dropTarget。 It will pick the text/plain DataFlavor instead of default text/html one; 它将选择文本/纯文本DataFlavor而不是默认的文本/ html文本;

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(): 使用initComponents()中的jEditorPane1对其进行初始化:

new JEditorPaneDropTarget(jEditorPane1); 

Here are no checks for possible null or cast exceptions, so you will need those too. 这里没有检查可能的null或强制转换异常,因此您也将需要这些。 Read something about DataFlavors and how to use them. 阅读有关DataFlavors及其使用方法的信息。 May be there is a way to mention right DataFlavor to use without writing whole custom DropTarget class, but i didn't find any. 可能有一种方法可以提及无需编写整个自定义DropTarget类即可使用的正确DataFlavor,但我没有找到任何方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM