学习使用SwingWorker

学习使用SwingWorker
2011年03月04日
   /*
  * 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, String> {
  private String userDir;
  private HashSet listeners = new HashSet();
  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 doInBackground() throws Exception {
  return FileUtil.searchPath(userDir, absoluteOrRelative);
  }
  @Override
  protected void done() {
  try {
  ArrayList al = this.get();
  for (FileSearchListener l : listeners) {
  l.processFileSearchOver(al);
  }
  } catch (InterruptedException ex) {
  Logger.getLogger(SwingWorkerFileSearch.class.getNa me()).log(Level.SEVERE, null, ex);
  } catch (ExecutionException ex) {
  Logger.getLogger(SwingWorkerFileSearch.class.getNa me()).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 searchPath(ArrayList 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 searchPath(File rootPath, int absoluteOrRelative) {
  ArrayList files = new ArrayList();
  searchPath(files, rootPath, rootPath.getPath(), absoluteOrRelative);
  return files;
  }
  public static ArrayList searchPath(String rootPath, int absoluteOrRelative) {
  ArrayList files = new ArrayList();
  searchPath(files, new File(rootPath), rootPath, absoluteOrRelative);
  return files;
  }
  private static void searchPath(ArrayList 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.SwingWorkerFileSearc h;
  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")
  //
  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.WindowConstan ts.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.Grou pLayout.Alignment.LEADING)
  .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 420, Short.MAX_VALUE)
  );
  jPanel2Layout.setVerticalGroup(
  jPanel2Layout.createParallelGroup(javax.swing.Grou pLayout.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.Grou pLayout.Alignment.LEADING)
  .addGroup(jPanel1Layout.createSequentialGroup()
  .addContainerGap()
  .addComponent(jButton1)
  .addPreferredGap(javax.swing.LayoutStyle.Component Placement.RELATED)
  .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 311, Short.MAX_VALUE)
  .addContainerGap())
  );
  jPanel1Layout.setVerticalGroup(
  jPanel1Layout.createParallelGroup(javax.swing.Grou pLayout.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();
  }//
  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 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 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();
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值