Java 自制图片批量处理小程序,Swing 拖拽,缩放 渲染图片。

主要功能就是可以浏览筛选的图片(可以拖拽放大),批量重命名,改尺寸,常见格式等,监听键盘事件可以通过方向键切换图片,空格键自动播放,delete键等方便超控一些功能。下载地址:源码和打包的.exe(直接运行)程序

预览
在这里插入图片描述

依赖

 	<!-- swing窗体美化包 -->
    <dependency>
      <groupId>com.formdev</groupId>
      <artifactId>flatlaf</artifactId>
      <version>3.1</version>
    </dependency>
    <!-- 图片处理工具类 -->
    <dependency>
      <groupId>net.coobird</groupId>
      <artifactId>thumbnailator</artifactId>
      <version>0.4.19</version>
    </dependency>

新建一个Swing GUI窗体,设计需要的布局内容。from布局和源码可以去前面下,下面只贴出部分代码内容。

在这里插入图片描述

筛选图片按钮功能,调用自带的 JFileChooser窗口(文件选择器)进行文件选择,处理分为单选和多选,对选中的文件夹进行递归,将所有jpg,png,jpeg 格式图片统计到arrImageList集合。


    /**
     * 筛选图片
     */
    private void scanPath() {
        JFileChooser chooser = new JFileChooser();
        chooser.setDialogTitle("筛选图片");
        chooser.setCurrentDirectory(new File(originalPath));
        chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        chooser.setMultiSelectionEnabled(true);
        设置文件过滤器(可选择的文件类型):默认所有文件
        chooser.setFileFilter();//设置默认使用的文件过滤器
     添加 文件过滤器
        chooser.addChoosableFileFilter(
                new FileNameExtensionFilter("zip(*.txt, *.rar, *.zip)", "txt", "rar", "zip"));//文件过滤器
        chooser.addChoosableFileFilter(
                new FileNameExtensionFilter("image(*.jpg,*.png,.gif)", "jpeg", "jpg", "png", "gif"));

        chooser.setApproveButtonText("选择");
        int state = chooser.showOpenDialog(null);
        if (state == JFileChooser.APPROVE_OPTION) {
            //     获取选择的文件流
            pathFiles = chooser.getSelectedFiles();
            scanPath(pathFiles);
        }
        imageHome.requestFocus();
    }
    
    /**
     * 筛选图片
     */
    private void scanPath(File[] files) {
        arrImageList = new ArrayList<>();
        arrPathList = new ArrayList<>();
        if (files.length == 1) {
            // 单选
            textPrefix.setText(files[0].getName());
        }

        for (File f : files) {
            if (f.isDirectory()) {
                // 文件夹时,递归查询子文件里的图片
                lookOverFile(f);
                arrPathList.add(f.getAbsolutePath());
            } else {
                final String[] split = f.getName().split("\\.");
                final String strType = split[split.length - 1].toLowerCase();
                if ("jpg".equals(strType)
                        || "png".equals(strType)
                        || "jpeg".equals(strType)) {
                    arrImageList.add(f.getAbsolutePath());
                }
            }
        }

        StringBuilder sb = new StringBuilder();
        for (String s : arrImageList) {
            s = s.replace(originalPath, "");
            sb.append(s).append("\n");
        }
        textArea1.setText(sb.toString());
        nCountImgsNum = arrImageList.size();
        ladelMessage.setText("-- 合计总数: \t " + nCountImgsNum);

        nIndex = 0;
        spinIndex.setValue(nIndex);
        initSetSpin();
        sliderIndex.setValue(nIndex);
        sliderIndex.setMaximum(nCountImgsNum);
        isSaveing = false;
        btnSaveing.setText("执行转存");

        if (isShowImgShow) {
            threaPreviewImage();
        }
        drawImage();

    }
    
    /**
     * 递归扫描路径文件
     */
    public void lookOverFile(File dir) {
        File[] subfiles = dir.listFiles();
        if (subfiles != null) {
            for (File f : subfiles) {
                if (f.isDirectory()) {
                    lookOverFile(f);
                    arrPathList.add(f.getAbsolutePath());
                } else {
                    final String[] split = f.getName().split("\\.");
                    final String strType = split[split.length - 1].toLowerCase();
                    if ("jpg".equals(strType)
                            || "png".equals(strType)
                            || "jpeg".equals(strType)) {
                        arrImageList.add(f.getAbsolutePath());
                    }
                }
            }
        }
    }

绘制图片,大致就是用线程池渲染显示图片,若预览图功能开启了,那会有一个另一个线程池预处理前后几张图片,并定期清除过远的预览图。这里就不贴了。


    /**
     * 上一张
     */
    void upShow() {
        if (arrImageList == null || nCountImgsNum == 0) {
            drawStr(Color.red, "当前图片数量为空!");
            imageHome.requestFocus();
            return;
        }
        nIndex = (int) spinIndex.getValue();
        spinIndex.setValue(getIndex(nIndex - 1));
        drawImage();
        imageHome.requestFocus();
    }

    /**
     * 下一张
     */
    private void downShow() {
        if (arrImageList == null || nCountImgsNum == 0) {
            drawStr(Color.red, "当前图片数量为空!");
            imageHome.requestFocus();
            return;
        }
        nIndex = (int) spinIndex.getValue();
        spinIndex.setValue(getIndex(nIndex + 1));

        drawImage();
        imageHome.requestFocus();
    }
	 /**
     * 渲染显示图片
     */
    private void drawImage() {
        if (arrImageList == null || nCountImgsNum == 0) {
            drawStr(Color.red, "当前图片数量为空!");
            return;
        }
        int indexValue = (int) spinIndex.getValue();
        nIndex = indexValue;
        sliderIndex.setValue(indexValue);
        threaDrawImage(indexValue);

    }

    /**
     * 线程 绘制图片
     */
    private void threaDrawImage(int index) {
        //创建线程池
        ThreadPoolExecutor threadDrawImage = new ThreadPoolExecutor(1, 1, 1, TimeUnit.SECONDS, new SynchronousQueue<>());
        //向线程池提交任务 无返回值
        int finalIndex = getIndex(index);
        threadDrawImage.execute(() -> {

            String path = arrImageList.get(finalIndex);
            try (
                    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path))
            ) {
                orgImage = ImageIO.read(bis);

            } catch (IOException e) {
                e.printStackTrace();
            }

            drawPictures();

            // 绘制预览图
            if (isShowImgShow) {
                int w = imgShow.getWidth() / 5;
                int h = w * 2 / 3;
                drawPreviewImage(img1.getGraphics(), finalIndex - 2, w, h, 10);
                drawPreviewImage(img2.getGraphics(), finalIndex - 1, w, h, 10);
                drawPreviewImage(img3.getGraphics(), finalIndex, w + 20, h + 20, 0);
                drawPreviewImage(img4.getGraphics(), finalIndex + 1, w, h, 10);
                drawPreviewImage(img5.getGraphics(), finalIndex + 2, w, h, 10);
            }
        });
        //关闭线程池
        threadDrawImage.shutdown();

    }


    /**
     * 绘制图片
     */
    private void drawPictures() {
        final Rectangle rect = drawPictures(orgImage);
        scale = rect.getWidth() / orgImage.getWidth();
        offsetX = (int) (rect.x / scale);
        offsetY = (int) (rect.y / scale);
    }

    /**
     * 绘制图片
     */
    private Rectangle drawPictures(BufferedImage image) {
        int width = imageShow.getWidth();
        int heigth = imageShow.getHeight();
        Graphics g = imageShow.getGraphics();

        drawImage = new BufferedImage(width, heigth, BufferedImage.TYPE_INT_RGB);
        final Graphics2D graphics = drawImage.createGraphics();
        graphics.setColor(imageHome.getBackground());
        graphics.fillRect(0, 0, drawImage.getWidth(), drawImage.getHeight());

        int x = 0;
        int y = 0;
        if (image != null) {
            try {
                image = Thumbnails.of(image).size(width, heigth).asBufferedImage();
                x = (width - image.getWidth()) / 2;
                y = (heigth - image.getHeight()) / 2;
                graphics.drawImage(image, x, y, null);
                g.drawImage(drawImage, 0, 0, null);

                return new Rectangle(x, y, image.getWidth(), image.getHeight());
            } catch (IOException e) {
                e.printStackTrace();
                return new Rectangle();
            }
        } else {
            g.drawImage(drawImage, 0, 0, null);
        }
        return new Rectangle();
    }

    /**
     * 绘制 预览图片
     */
    private void drawPreviewImage(Graphics g, int imgIndex, int width, int heigth, int y) {
        BufferedImage images = new BufferedImage(width, heigth, BufferedImage.TYPE_INT_RGB);
        final Graphics2D graphics = images.createGraphics();
        graphics.setColor(imageHome.getBackground());
        graphics.fillRect(0, 0, images.getWidth(), images.getHeight());

        int x = 0;
        BufferedImage img = hasPreproImage.get(getIndex(imgIndex));
        if (img != null) {
            try {
                img = Thumbnails.of(img).size(width, heigth).asBufferedImage();
                x = (width - img.getWidth()) / 2;
                graphics.drawImage(img, x, y, null);

                g.drawImage(images, 0, 0, null);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            g.drawImage(images, 0, 0, null);
        }
    }

缩放拖拽功能实现,这个监听事件(按下,松开,滚轮等)的逻辑要弄好,具体的缩放拖拽功能有两种实现,第一种就是 利用缩放画布绘制 ,第二种是 计算参数 用 Thumbnails.精确裁剪缩放,第二种画质好些,但是计算参数算法还有点偏差,有改进的建议或者更好的方法可以写评论。


    /**
     * 图片缩放功能
     */
    private void zoomDrawImage(MouseWheelEvent e) {

        double ratio = scale;
        if (e.getWheelRotation() < 0) {
            // 滚轮向上,放大画布
            scale *= 1.1;
        } else {
            // 滚轮向下,缩小画布
            scale /= 1.1;
        }
        /** 调整偏移量 */
        offsetX += (int) (e.getX() * (1 / scale - 1 / ratio));
        offsetY += (int) (e.getY() * (1 / scale - 1 / ratio));


        // 重新绘图
        drawImageXY();
    }

    /**
     * 拖放图片
     */
    private void moveImage(MouseEvent e) {
        if (!isMoveing) {
            return;
        }

        // 统计本次鼠标移动的相对值
        int dx = e.getX() - startX;
        int dy = e.getY() - startY;

        // 偏移量累加
        offsetX += (int) (dx / scale);
        offsetY += (int) (dy / scale);

        // 记录当前拖动后的位置
        startX += dx;
        startY += dy;

        // 重新绘图
        drawImageXY();
    }

    /**
     * 绘制图片 
     * 根据指定的缩放拖拽方式,以线程方式执行
     */
    private void drawImageXY() {
        //创建线程池
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        //向线程池提交任务 有返回值
        executorService.execute(() -> {
            if (RadZooming.isSelected()) {
                drawImageXY2();
            } else {
                drawImageXY1();
            }
        });
        //关闭线程池
        executorService.shutdown();
    }

    /**
     * 绘制图片 1
     * 利用 缩放画布绘制 
     */
    private void drawImageXY1() {
        if (orgImage == null) {
            return;
        }

        Graphics2D g = (Graphics2D) imageShow.getGraphics();
        // 缩放画布
        g.scale(scale, scale);
        // 拖动画布
//        g.translate(offsetX, offsetY);
//        g.drawImage(image, offsetX, offsetY, null);

        // 缓冲图上绘制图片然后绘制至面板
        BufferedImage imgs = new BufferedImage((int) (imageShow.getWidth() / scale), (int) (imageShow.getHeight() / scale), BufferedImage.TYPE_INT_RGB);
        final Graphics2D g2D = imgs.createGraphics();
        g2D.setColor(imageHome.getBackground());
        g2D.fillRect(0, 0, imgs.getWidth(), imgs.getHeight());
        g2D.drawImage(orgImage, offsetX, offsetY, null);
        drawImage = imgs;
        g.drawImage(imgs, 0, 0, null);
    }

    /**
     * 绘制图片 2
     * 计算参数 用 Thumbnails.精确裁剪缩放
     */
    private void drawImageXY2() {
        if (orgImage == null) {
            return;
        }
        int drawX = 0;
        int drawY = 0;
        int clipX = 0;
        int clipY = 0;
        int clipW = (int) (imageShow.getWidth() / scale);
        int clipH = (int) (imageShow.getHeight() / scale);
        if (offsetX < 0) {
            clipX = -offsetX;
        } else {
            drawX = (int) (offsetX * scale);
        }
        if (offsetY < 0) {
            clipY = -offsetY;
        } else {
            drawY = (int) (offsetY * scale);
        }
        Graphics2D g = (Graphics2D) imageShow.getGraphics();
        // 缓冲图上绘制图片然后绘制至面板
        BufferedImage images = new BufferedImage(imageShow.getWidth(), imageShow.getHeight(), BufferedImage.TYPE_INT_RGB);
        final Graphics2D g2D = images.createGraphics();
        g2D.setColor(imageHome.getBackground());
        g2D.fillRect(0, 0, images.getWidth(), images.getHeight());
        if (clipX < orgImage.getWidth() && clipY < orgImage.getHeight()) {
            if (clipW - offsetX > orgImage.getWidth()) {
                clipW = orgImage.getWidth() - clipX;
            }
            if (clipH - offsetY > orgImage.getHeight()) {
                clipH = orgImage.getHeight() - clipY;
            }
            BufferedImage imgs = null;
            try {
                imgs = Thumbnails.of(orgImage).sourceRegion(clipX, clipY, clipW, clipH).size((int) (clipW * scale), (int) (clipH * scale)).asBufferedImage();
            } catch (IOException e) {
                e.printStackTrace();
            }
            g2D.drawImage(imgs, drawX, drawY, null);
        }
        g.drawImage(images, 0, 0, null);
        drawImage = images;
    }


键盘监听事件

主要就是让一个布局内容获得焦点,在所有事件里加一句 imageHome.requestFocus();请求焦点。

这里触发的事件就不一一贴代码了


/**
     * 键值响应
     */
    private void imageShowKeyReleased(int code) {
//        System.out.println("键值 : " + code);
       /*
             45  - ;61 + ;
             < 37; ^ 38;  > 39 ;v 40;
             A  65; W  87;D   68;S  83;
             空格 32;  删除 8 ;delete 127;
             10 回车
        */
        if (code == 27) {
            isShowBtnSetup = !isShowBtnSetup;
            btnSetup.setVisible(isShowBtnSetup);
            if (isShowBtnSetup) {
                btnSetup.updateUI();
            }
        } else if (code == 20) {
            isShowImgShow = !isShowImgShow;
            chkPreview.setSelected(isShowImgShow);
            imgShow.setVisible(isShowImgShow);
            if (isShowImgShow) {
                imgShow.updateUI();
                threaPreviewImage();
            }
            drawImage();
        } else if (code == 37 || code == 38 || code == 65 || code == 87) {
            upShow();
        } else if (code == 39 || code == 40 || code == 68 || code == 83) {
            downShow();
        } else if (code == 32) {
            threaPlayDrawImage();
        } else if (code == 10) {
            saveOneImg();
        } else if (code == 127) {
            dleteOneImg();
        } else if (code == 8) {
            removeOneImg();
        } else if (code == 61) {
            sleepTime = sliderSleep.getValue() + 200;
            sliderSleep.setValue(Math.toIntExact(Math.min(sleepTime, sliderSleep.getMaximum())));
        } else if (code == 45) {
            sleepTime = sliderSleep.getValue() - 200;
            sliderSleep.setValue(Math.toIntExact(Math.max(sleepTime, sliderSleep.getMinimum())));
        }
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
实现文件的拖拽功能 import java.awt.AlphaComposite; import java.awt.Component; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DragGestureEvent; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DragSource; import java.awt.dnd.DragSourceDragEvent; import java.awt.dnd.DragSourceDropEvent; import java.awt.dnd.DragSourceEvent; import java.awt.dnd.DragSourceListener; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.swing.Icon; import javax.swing.JLabel; import javax.swing.JTree; import javax.swing.Timer; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.filechooser.FileSystemView; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; class DragTree extends JTree implements DragGestureListener, DragSourceListener, DropTargetListener { /** * */ private static final long serialVersionUID = 1L; BufferedImage ghostImage; private Rectangle2D ghostRect = new Rectangle2D.Float(); private Point ptOffset = new Point(); private Point lastPoint = new Point(); private TreePath lastPath; private Timer hoverTimer; FileNode sourceNode; public DragTree() { DragSource dragSource = DragSource.getDefaultDragSource(); dragSource.createDefaultDragGestureRecognizer(this, // component where // drag originates DnDConstants.ACTION_COPY_OR_MOVE, // actions this); // drag gesture recognizer setModel(createTreeModel()); addTreeExpansionListener(new TreeExpansionListener() { public void treeCollapsed(TreeExpansionEvent e) { } public void treeExpanded(TreeExpansionEvent e) { TreePath path = e.getPath(); if (path != null) { FileNode node = (FileNode) path.getLastPathComponent(); if (!node.isExplored()) { DefaultTreeModel model = (DefaultTreeModel) getModel(); node.explore(); model.nodeStructureChanged(node); } } } }); this.setCellRenderer(new DefaultTreeCellRenderer() { public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { TreePath tp = tree.getPathForRow(row); if (tp != null) { FileNode node = (FileNode) tp.getLastPathComponent(); File f = node.getFile(); try { Icon icon = FileSystemView.getFileSystemView() .getSystemIcon(f); this.setIcon(icon); this.setLeafIcon(icon); this.setOpenIcon(icon); this.setClosedIcon(icon); this.setDisabledIcon(icon); } catch (Exception e) { e.printStackTrace(); } } return super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); } }); super.setScrollsOnExpand(true); new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this); // Set up a hover timer, so that a node will be automatically expanded // or collapsed // if the user lingers on it for more than a short time hoverTimer = new Timer(1000, new ActionListener() { public void actionPerformed(ActionEvent e) { if (lastPath == null) { return; } if (getRowForPath(lastPath) == 0) return; // Do nothing if we are hovering over the root node if (isExpanded(lastPath)) collapsePath(lastPath); else expandPath(lastPath); } }); hoverTimer.setRepeats(false); // Set timer to one-shot mode this.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { int code = e.getKeyCode(); int modifiers = e.getModifiers(); if (code == 'v' || code == 'V') { System.out.println("find v"); System.out.println("modifiers:" + modifiers + "\t" + ((modifiers & KeyEvent.CTRL_MASK) != 0)); } if ((modifiers & KeyEvent.CTRL_MASK) != 0 && (code == 'v' || code == 'V')) { Transferable tr = Toolkit.getDefaultToolkit() .getSystemClipboard().getContents(null); TreePath path = getSelectionPath(); if (path == null) { return; } FileNode node = (FileNode) path.getLastPathComponent(); if (node.isDirectory()) { System.out.println("file cp"); try { List list = (List) (tr .getTransferData(DataFlavor.javaFileListFlavor)); Iterator iterator = list.iterator(); File parent = node.getFile(); while (iterator.hasNext()) { File f = (File) iterator.next(); cp(f, new File(parent, f.getName())); } node.reexplore(); } catch (Exception ioe) { ioe.printStackTrace(); } updateUI(); } } } }); } public void dragGestureRecognized(DragGestureEvent e) { // drag anything ... TreePath path = getLeadSelectionPath(); if (path == null) return; FileNode node = (FileNode) path.getLastPathComponent(); sourceNode = node; // Work out the offset of the drag point from the TreePath bounding // rectangle origin Rectangle raPath = getPathBounds(path); Point ptDragOrigin = e.getDragOrigin(); ptOffset.setLocation(ptDragOrigin.x - raPath.x, ptDragOrigin.y - raPath.y); // Get the cell renderer (which is a JLabel) for the path being dragged int row = this.getRowForLocation(ptDragOrigin.x, ptDragOrigin.y); JLabel lbl = (JLabel) getCellRenderer().getTreeCellRendererComponent( this, // tree path.getLastPathComponent(), // value false, // isSelected (dont want a colored background) isExpanded(path), // isExpanded getModel().isLeaf(path.getLastPathComponent()), // isLeaf row, // row (not important for rendering) false // hasFocus (dont want a focus rectangle) ); lbl.setSize((int) raPath.getWidth(), (int) raPath.getHeight()); // <-- // The // layout // manager // would // normally // do // this // Get a buffered image of the selection for dragging a ghost image this.ghostImage = new BufferedImage((int) raPath.getWidth(), (int) raPath.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE); Graphics2D g2 = ghostImage.createGraphics(); // Ask the cell renderer to paint itself into the BufferedImage g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 0.5f)); // Make the image ghostlike lbl.paint(g2); g2.dispose(); // this.getGraphics().drawImage(ghostImage, e.getDragOrigin().x, // e.getDragOrigin().y, this); e.startDrag( null, // cursor ghostImage, new Point(5, 5), new StringSelection(getFilename()), // transferable this); // drag source listener } public void dragDropEnd(DragSourceDropEvent e) { ghostImage = null; sourceNode = null; } public void dragEnter(DragSourceDragEvent e) { } public void dragExit(DragSourceEvent e) { if (!DragSource.isDragImageSupported()) { repaint(ghostRect.getBounds()); } } public void dragOver(DragSourceDragEvent e) { } public void dropActionChanged(DragSourceDragEvent e) { } public String getFilename() { TreePath path = getLeadSelectionPath(); FileNode node = (FileNode) path.getLastPathComponent(); return ((File) node.getUserObject()).getAbsolutePath(); } private DefaultTreeModel createTreeModel() { File root = FileSystemView.getFileSystemView().getRoots()[0]; FileNode rootNode = new FileNode(root); rootNode.explore(); return new DefaultTreeModel(rootNode); } public void dragEnter(DropTargetDragEvent dtde) { } public void dragOver(DropTargetDragEvent dtde) { Point pt = dtde.getLocation(); if (pt.equals(lastPoint)) { return; } if (ghostImage != null) { Graphics2D g2 = (Graphics2D) getGraphics(); // If a drag image is not supported by the platform, then draw my // own drag image if (!DragSource.isDragImageSupported()) { paintImmediately(ghostRect.getBounds()); // Rub out the last // ghost image and cue // line // And remember where we are about to draw the new ghost image ghostRect.setRect(pt.x - ptOffset.x, pt.y - ptOffset.y, ghostImage.getWidth(), ghostImage.getHeight()); g2.drawImage((ghostImage), AffineTransform .getTranslateInstance(ghostRect.getX(), ghostRect.getY()), null); } } TreePath path = getClosestPathForLocation(pt.x, pt.y); if (!(path == lastPath)) { lastPath = path; hoverTimer.restart(); } } public void dropActionChanged(DropTargetDragEvent dtde) { } public void drop(DropTargetDropEvent e) { try { DataFlavor stringFlavor = DataFlavor.stringFlavor; Transferable tr = e.getTransferable(); TreePath path = this.getPathForLocation(e.getLocation().x, e.getLocation().y); if (path == null) { e.rejectDrop(); return; } FileNode node = (FileNode) path.getLastPathComponent(); if (e.isDataFlavorSupported(DataFlavor.javaFileListFlavor) && node.isDirectory()) { e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); System.out.println("file cp"); List list = (List) (e.getTransferable() .getTransferData(DataFlavor.javaFileListFlavor)); Iterator iterator = list.iterator(); File parent = node.getFile(); while (iterator.hasNext()) { File f = (File) iterator.next(); cp(f, new File(parent, f.getName())); } node.reexplore(); e.dropComplete(true); this.updateUI(); } else if (e.isDataFlavorSupported(stringFlavor) && node.isDirectory()) { String filename = (String) tr.getTransferData(stringFlavor); if (filename.endsWith(".txt") || filename.endsWith(".java") || filename.endsWith(".jsp") || filename.endsWith(".html") || filename.endsWith(".htm")) { e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); File f = new File(filename); if (f.exists()) { f.renameTo(new File(node.getFile(), f.getName())); node.reexplore(); ((FileNode) sourceNode.getParent()).remove(sourceNode); e.dropComplete(true); this.updateUI(); } else { e.rejectDrop(); } } else { e.rejectDrop(); } } else { e.rejectDrop(); } } catch (IOException ioe) { ioe.printStackTrace(); } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); } finally { ghostImage = null; this.repaint(); } } private void cp(File src, File dest) throws IOException { if (src.isDirectory()) { if (!dest.exists()) { boolean ret = dest.mkdir(); if (ret == false) return; } File[] fs = src.listFiles(); for (int i = 0; i < fs.length; i++) { cp(fs[i], new File(dest, fs[i].getName())); } return; } byte[] buf = new byte[1024]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); int len; try { while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } finally { in.close(); out.close(); } } public void dragExit(DropTargetEvent dte) { } } class FileNode extends DefaultMutableTreeNode { private boolean explored = false; public FileNode(File file) { setUserObject(file); } public boolean getAllowsChildren() { return isDirectory(); } public boolean isLeaf() { return !isDirectory(); } public File getFile() { return (File) getUserObject(); } public boolean isExplored() { return explored; } public boolean isDirectory() { File file = getFile(); return file.isDirectory(); } public String toString() { File file = (File) getUserObject(); String filename = file.toString(); int index = filename.lastIndexOf(File.separator); return (index != -1 && index != filename.length() - 1) ? filename .substring(index + 1) : filename; } public void explore() { if (!isDirectory()) return; if (!isExplored()) { File file = getFile(); File[] children = file.listFiles(); for (int i = 0; i < children.length; ++i) { if (children[i].isDirectory()) add(new FileNode(children[i])); } for (int i = 0; i < children.length; ++i) { if (!children[i].isDirectory()) add(new FileNode(children[i])); } explored = true; } } public void reexplore() { this.removeAllChildren(); explored = false; explore(); } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值