学习使用SwingWorker

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cn.feelingsoft.photomgr.model;

import cn.feelingsoft.photomgr.i.FileSearchListener;
import cn.feelingsoft.photomgr.util.FileUtil;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.SwingWorker;

/**
*
* @author Sanwu
*/
public class SwingWorkerFileSearch extends SwingWorker<ArrayList<String>, String> {

    private String userDir;
    private HashSet<FileSearchListener> listeners = new HashSet<FileSearchListener>();
    private int absoluteOrRelative;

    public SwingWorkerFileSearch() {
        this("", FileUtil.ABSOLUTEPATH);
    }

    public SwingWorkerFileSearch(String userDir) {
        this(userDir, FileUtil.ABSOLUTEPATH);
    }

    public SwingWorkerFileSearch(String userDir, int absoluteOrRelative) {
        this.userDir = userDir;
        this.absoluteOrRelative = absoluteOrRelative;
    }

    @Override
    protected ArrayList<String> doInBackground() throws Exception {
        return FileUtil.searchPath(userDir, absoluteOrRelative);
    }

    @Override
    protected void done() {
        try {
            ArrayList<String> al = this.get();
            for (FileSearchListener l : listeners) {
                l.processFileSearchOver(al);
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(SwingWorkerFileSearch.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ExecutionException ex) {
            Logger.getLogger(SwingWorkerFileSearch.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void addFileSearchListener(FileSearchListener listener) {
        if (null != listener) {
            this.listeners.add(listener);
        }
    }

    public void removeFileSearchListener(FileSearchListener listener) {
        if (null != listener) {
            listeners.remove(listener);
        }
    }

    public String getUserDir() {
        return userDir;
    }

    public void setUserDir(String userDir) {
        this.userDir = userDir;
    }
}


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package cn.feelingsoft.photomgr.util;

import java.io.File;
import java.util.ArrayList;

/**
*
* @author Sanwu
*/
public class FileUtil {

    public final static int ABSOLUTEPATH = 1;
    public final static int RELATIVEPATH = 2;

//    public static ArrayList<String> searchPath(ArrayList<String> filenames, File rootPath) {
//
//        if (rootPath.exists() && rootPath.isDirectory()) {
//            String[] subPathFilenames = rootPath.list();
//            for (String filename : subPathFilenames) {
//                File file = new File(rootPath.getPath() + File.separator + filename);
//                if (file.isDirectory()) {
//                    searchPath(filenames, file);
//                } else {
//                    filenames.add(file.getAbsolutePath());
//                }
//            }
//        } else if (rootPath.isFile()) {
//            filenames.add(rootPath.getPath() + File.separator + rootPath.getName());
//        }
//
//        return filenames;
//    }

    public static ArrayList<String> searchPath(File rootPath, int absoluteOrRelative) {
        ArrayList<String> files = new ArrayList<String>();
        searchPath(files, rootPath, rootPath.getPath(), absoluteOrRelative);
       
        return files;
    }
    public static ArrayList<String> searchPath(String rootPath, int absoluteOrRelative) {
        ArrayList<String> files = new ArrayList<String>();
        searchPath(files, new File(rootPath), rootPath, absoluteOrRelative);

        return files;
    }


    private static void searchPath(ArrayList<String> filenames, File cRootPath, String rootPath, int absoluteOrRelative) {

        if (cRootPath.exists() && cRootPath.isDirectory()) {
            String[] subPathFilenames = cRootPath.list();
            for (String filename : subPathFilenames) {
                File file = new File(cRootPath.getPath() + File.separator + filename);
                if (file.isDirectory()) {
                    searchPath(filenames, file, rootPath, absoluteOrRelative);
                } else if(absoluteOrRelative == FileUtil.RELATIVEPATH) {
                    filenames.add(StringUtil.getRelativePath(rootPath, file.getAbsolutePath()));
                } else if (absoluteOrRelative == FileUtil.ABSOLUTEPATH) {
                    filenames.add(file.getAbsolutePath());
                }
            }
        } else if (cRootPath.isFile()) {
            if (absoluteOrRelative == FileUtil.ABSOLUTEPATH) {
                filenames.add(cRootPath.getAbsolutePath());
            } else {
                filenames.add(StringUtil.getRelativePath(rootPath, cRootPath.getAbsolutePath()));
            }
        }
    }

   
}


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cn.feelingsoft.photomgr.util;

import java.io.File;

/**
*
* @author Sanwu
*/
public class StringUtil {

    public static String getRelativePath(String rootPath, String absolutePath) {
        if (null == rootPath
                || null == absolutePath
                || rootPath.trim().equals("")
                || absolutePath.trim().equals("")) {
            return null;
        }

        //统一表示格式
        rootPath = new File(rootPath).getPath();
        absolutePath = new File(absolutePath).getAbsolutePath();

        if (absolutePath.startsWith(rootPath)){
            return absolutePath.substring(rootPath.length());
        }

        return null;
    }

   
}

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/*
* MainJFrame1.java
*
* Created on 2011-3-4, 10:26:15
*/
package cn.feelingsoft.photomgr.ui;

import cn.feelingsoft.photomgr.i.FileSearchListener;
import cn.feelingsoft.photomgr.model.SwingWorkerFileSearch;
import java.util.ArrayList;

/**
*
* @author Sanwu
*/
public class MainJFrame1 extends javax.swing.JFrame implements FileSearchListener {

    /** Creates new form MainJFrame1 */
    public MainJFrame1() {
        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() {

        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextAreaSearchResult = new javax.swing.JTextArea();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextAreaSearchResult.setColumns(20);
        jTextAreaSearchResult.setEditable(false);
        jTextAreaSearchResult.setRows(5);
        jTextAreaSearchResult.setTabSize(4);
        jTextAreaSearchResult.setFocusable(false);
        jScrollPane1.setViewportView(jTextAreaSearchResult);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 420, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 183, Short.MAX_VALUE)
        );

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane2.setViewportView(jTextArea1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(1, 1, 1)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        jTextArea1.append("button clicked.\n");
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                MainJFrame1 mf = new MainJFrame1();
                mf.setVisible(true);
            }
        });
        new SwingWorkerFileSearch().execute();

    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextArea jTextAreaSearchResult;
    // End of variables declaration


    public void processFileSearchOver(ArrayList<String> arrayList) {
        for (String str : arrayList) {
            jTextAreaSearchResult.append(str + "\n");
        }

    }
}


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package cn.feelingsoft.photomgr.i;

import java.util.ArrayList;

/**
*
* @author Sanwu
*/
public interface FileSearchListener {

    void processFileSearchOver(ArrayList<String> arrayList);


}


以下是测试代码

    public static void main(String[] args) {
        final String userDir = "H:/客户照片";

        MainJFrame1 mf = new MainJFrame1();
        SwingWorkerFileSearch swfs = new SwingWorkerFileSearch(userDir, FileUtil.ABSOLUTEPATH);
        swfs.addFileSearchListener(mf);

        mf.setVisible(true);
        swfs.execute();
    }

你可能感兴趣的:(UI,swing)