@Override
protected void done() {
if (progressHandle != null) {
progressHandle.processComplete(contacts);
}
}
客户端如何来使用用SwingWork呢,很简单,只需要新建一个实例并且调用它的execute方法即可,他会自动调用doInBackground方法来完成操作;以下是完整的代码实现:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package swingworkertest;
/**
*
* @author Administrator
*/
public class BeanContact {
private String name=null;
private String sex=null;
private String phone=null;
private String email=null;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the sex
*/
public String getSex() {
return sex;
}
/**
* @param sex the sex to set
*/
public void setSex(String sex) {
this.sex = sex;
}
/**
* @return the phone
*/
public String getPhone() {
return phone;
}
/**
* @param phone the phone to set
*/
public void setPhone(String phone) {
this.phone = phone;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* Contacts.java
*
* Created on 2011-6-25, 10:40:13
*/
package swingworkertest;
import javax.swing.JFileChooser;
/**
*
* @author Administrator
*/
public class Contacts extends javax.swing.JFrame {
/** Creates new form Contacts */
public Contacts() {
initComponents();
handle = new DefaultProgressHandle();
handle.setTable(jTable1);
handle.setProgressBar(jProgressBar1);
}
/** 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() {
jButton1 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton2 = new javax.swing.JButton();
jProgressBar1 = new javax.swing.JProgressBar();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("浏览");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTextField1.setEditable(false);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"姓名", "性别", "电话", "电子邮件"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jScrollPane1.setViewportView(jTable1);
jButton2.setText("加载联系人");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE)
.addComponent(jProgressBar1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 557, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 442, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jButton1, jButton2, jTextField1});
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
ContactsFileFilter filter = new ContactsFileFilter();
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION){
jTextField1.setText(chooser.getSelectedFile().getAbsolutePath());
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
LoadContactsTask task = new LoadContactsTask(jTextField1.getText());
task.setProgressHandle(handle);
task.execute();
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Contacts contacts = new Contacts();
contacts.setTitle("Contacts");;
contacts.setVisible(true);
}
});
}
DefaultProgressHandle handle = null;
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JProgressBar jProgressBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package swingworkertest;
import java.io.File;
import javax.swing.filechooser.FileFilter;
/**
*
* @author Administrator
*/
public class ContactsFileFilter extends FileFilter{
public boolean accept(File pathname) {
if(pathname.isDirectory()){
return true;
}else{
return pathname.getName().endsWith(".cff");
}
}
@Override
public String getDescription() {
return "Text Files";
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package swingworkertest;
import java.util.List;
import javax.swing.JProgressBar;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Administrator
*/
public class DefaultProgressHandle implements IProgressHandle {
private JTable table = null;
private JProgressBar progressBar = null;
public void processInProgress(List<BeanContact> contacts, int progress) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
for (BeanContact contact : contacts) {
String[] strArray = {contact.getName(), contact.getSex(), contact.getPhone(), contact.getEmail()};
model.addRow(strArray);
}
progressBar.setValue(progress);
}
public void processComplete(List<BeanContact> contacts) {
progressBar.setValue(progressBar.getMaximum());
}
/**
* @param table the table to set
*/
public void setTable(JTable table) {
this.table = table;
}
/**
* @param progressBar the progressBar to set
*/
public void setProgressBar(JProgressBar progressBar) {
this.progressBar = progressBar;
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package swingworkertest;
import java.util.List;
/**
*
* @author Administrator
*/
public interface IProgressHandle {
public abstract void processInProgress(List<BeanContact> contacts,int progress);
public abstract void processComplete(List<BeanContact> contacts);
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package swingworkertest;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import javax.swing.SwingWorker;
/**
*
* @author Administrator
*/
public class LoadContactsTask extends SwingWorker<List<BeanContact>, BeanContact> {
private String fileName = null;
private IProgressHandle progressHandle = null;
private List<BeanContact> contacts = null;
private int lineCnt = 0;
public LoadContactsTask(String fileName) {
this.fileName = fileName;
contacts = new ArrayList<BeanContact>();
}
@Override
protected List<BeanContact> doInBackground() throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("c:/contacts.cff"));
String line = null;
while ((line = reader.readLine()) != null) {
String[] strContacts = line.split(",");
BeanContact contact = new BeanContact();
contact.setName(strContacts[0]);
contact.setSex(strContacts[1]);
contact.setPhone(strContacts[2]);
contact.setEmail(strContacts[3]);
lineCnt++;
publish(contact);
contacts.add(contact);
Thread.sleep(100);
}
return contacts;
}
/**
* @param progressHandle the progressHandle to set
*/
public void setProgressHandle(IProgressHandle progressHandle) {
this.progressHandle = progressHandle;
}
@Override
protected void process(List<BeanContact> chunks) {
if (progressHandle != null) {
progressHandle.processInProgress(chunks, lineCnt * 100 / 10000);
}
}
@Override
protected void done() {
if (progressHandle != null) {
progressHandle.processComplete(contacts);
}
}
}