java

位置:IT落伍者 >> java >> 浏览文章

Java拖放文件到Swing窗口


发布日期:2023年10月12日
 
Java拖放文件到Swing窗口

经过测试是没有问题的

代码

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;

// 变量声明结束

}

               

上一篇:Java2下Applet数字签名

下一篇:JAVA编程语言程序开发平方