熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java拖放文件到Swing窗口

2013-11-23 19:07:49  來源: Java核心技術 

  經過測試是沒有問題的

  代碼

  package comtestui;

  import javaawtdatatransferDataFlavor;

  import javaawtdatatransferUnsupportedFlavorException;

  import javaawtdndDnDConstants;

  import javaawtdndDropTarget;

  import javaawtdndDropTargetDragEvent;

  import javaawtdndDropTargetDropEvent;

  import javaawtdndDropTargetEvent;

  import javaawtdndDropTargetListener;

  import javaioFile;

  import javaioIOException;

  import javautilIterator;

  import javautilList;

  import javaxswingJTextArea;

  public class DragFile extends javaxswingJFrame {

  public DragFile() {

  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

  */

  // <editorfold defaultstate=collapsed desc= 生成的代碼 >

  private void initComponents() {

  jScrollPane = new javaxswingJScrollPane();

  jTextArea = new MyTextArea();

  setDefaultCloseOperation(javaxswingWindowConstantsEXIT_ON_CLOSE);

  jTextAreasetColumns();

  jTextAreasetRows();

  jScrollPanesetViewportView(jTextArea);

  getContentPane()add(jScrollPane javaawtBorderLayoutCENTER);

  pack();

  }// </editorfold>

  /**

  * @param args

  *            the command line arguments

  */

  public static void main(String args[]) {

  javaawtEventQueueinvokeLater(new Runnable() {

  public void run() {

  new DragFile()setVisible(true);

  }

  });

  }

  class MyTextArea extends JTextArea implements DropTargetListener {

  public MyTextArea() {

  new DropTarget(this DnDConstantsACTION_COPY_OR_MOVE this);

  }

  public void dragEnter(DropTargetDragEvent dtde) {

  }

  public void dragOver(DropTargetDragEvent dtde) {

  }

  public void dropActionChanged(DropTargetDragEvent dtde) {

  }

  public void dragExit(DropTargetEvent dte) {

  }

  public void drop(DropTargetDropEvent dtde) {

  try {

  // Transferable tr = dtdegetTransferable();

  if (dtdeisDataFlavorSupported(DataFlavorjavaFileListFlavor)) {

  dtdeacceptDrop(DnDConstantsACTION_COPY_OR_MOVE);

  List list = (List) (dtdegetTransferable()getTransferData(DataFlavorjavaFileListFlavor));

  Iterator iterator = erator();

  while (iteratorhasNext()) {

  File f = (File) iteratornext();

  thisappend(fgetAbsolutePath() + \n);

  }

  dtdedropComplete(true);

  thisupdateUI();

  } else {

  dtderejectDrop();

  }

  } catch (IOException ioe) {

  ioeprintStackTrace();

  } catch (UnsupportedFlavorException ufe) {

  ufeprintStackTrace();

  }

  }

  }

  // 變量聲明 不進行修改

  private javaxswingJScrollPane jScrollPane;

  private javaxswingJTextArea jTextArea;

  // 變量聲明結束

  }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/26318.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.