将方法移动到SwingWorker中

时间:2014-08-10 20:29:28

标签: java swing file-io jtable swingworker

我正在研究一种分析DNA的程序。该程序的主要工作是采用某种文件类型的方法,解析文件并将其转换为字符串,然后解析字符串以将其分成段。然后,它会在新JTable上的JFrame中返回分析结果。

public  JTable readFile(File file) throws IOException{
    BufferedReader in = new BufferedReader(new FileReader(file));
    String line;
    String result = "";
    while((line=in.readLine())!=null) {
       if(!line.startsWith(">")) {
              result = result + line;
               }            
    }       

    Sequence sequence = new Sequence("Unspecified", result);
    ArrayList<Contig> contigs = sequence.getReadingFrames();

    String [] columnNames = {"Position", "Frame", "Sequence"};

     Object[][] data = new Object[contigs.size()][3];
     int j = 0;
    for (int i = 0; i <= contigs.size() && j < 3; i++){
        if (i == contigs.size()){
            j++;
            i = -1;
        }
        else if (j == 0){
            data[i][j] = Integer.toString(contigs.get(i).getStartPosition());   
        }
        else if (j == 1){
            data[i][j] = Integer.toString(contigs.get(i).getReadingFrame());
        }
        else if (j == 2){
            data[i][j] = contigs.get(i).getSequence();
        }
    }
    JTable seqTable = new JTable(data, columnNames);
    in.close();
    return seqTable;
}

我应该如何将其移至SwingWorker?我尝试了复制,粘贴和编辑,但整个过程只返回空结果。

3 个答案:

答案 0 :(得分:2)

我实际上有一个与“My-Name-Is”非常相似的答案,尽管我试图显示执行流程并且不会迷失在细节中,但我已经简化了很多。

基本上,如果“整个事情只返回空结果”,我想也许你可能搞砸了从后台线程到GUI线程的交接。仔细检查您的done()方法,确保正确拨打get()

还要记住,Swing不是线程安全的,所有GUI组件(即你的JTable)都必须在EDT上构建,在这种情况下,它意味着在done()方法中,而不是在背景中线程。

class TableBuilder extends SwingWorker<Object[][], Void> {
   private final String [] columnNames = {"Position", "Frame", "Sequence"};

   @Override
   public Object[][] doInBackground() throws Exception {
      // read your file, and build your data object...
      Object[][] data = new Object[someSize()][3];
      // then return it to the EDT ...
      return data;
   }
   @Override
   public void done() {
      // now on the EDT, build your GUI components, and 
      // update the GUI as needed.
      try {
         Object[][] data = get();
         JTable seqTable = new JTable(data, columnNames);
         // add your seqTable to the gui here...
      } catch (InterruptedException | ExecutionException ex) {
         // exit
      }
   }
}

答案 1 :(得分:2)

你至少有三个选择,你可以......

使用publish / process填充预先存在的TableModel ...

public class TableBuilder extends SwingWorker<Object[][], Object[]> {

    private DefaultTableModel tableModel;

    public TableBuilder(DefaultTableModel tableModel) {
        this.tableModel = tableModel;
    }

    @Override
    protected Object[][] doInBackground() throws Exception {
        try (BufferedReader in = new BufferedReader(new FileReader(file))) {
            String line;
            String result = "";
            while ((line = in.readLine()) != null) {
                if (!line.startsWith(">")) {
                    result = result + line;
                }
            }

            Sequence sequence = new Sequence("Unspecified", result);
            ArrayList<Contig> contigs = sequence.getReadingFrames();

            Object[][] data = new Object[contigs.size()][3];
            int j = 0;
            for (int i = 0; i <= contigs.size() && j < 3; i++) {
                if (i == contigs.size()) {
                    j++;
                    i = -1;
                } else if (j == 0) {
                    data[i][j] = Integer.toString(contigs.get(i).getStartPosition());
                } else if (j == 1) {
                    data[i][j] = Integer.toString(contigs.get(i).getReadingFrame());
                } else if (j == 2) {
                    data[i][j] = contigs.get(i).getSequence();
                }
                publish(data[i]);
            }
        }
        return data;
    }

    @Override
    protected void process(List<Object[]> chunks) {
        for (Object[] row : chunks) {
            tableModel.addRow(row);
        }
    }

}

TableModel方法中构建doInBackground ...

public class TableBuilder extends SwingWorker<TableModel, Void> {

    private JTable table;

    public TableBuilder(JTable table) {
        this.table = table;
    }

    @Override
    protected TableModel doInBackground() throws Exception {
        DefaultTableModel tableModel;
        try (BufferedReader in = new BufferedReader(new FileReader(file))) {
            String line;
            String result = "";
            while ((line = in.readLine()) != null) {
                if (!line.startsWith(">")) {
                    result = result + line;
                }
            }

            Sequence sequence = new Sequence("Unspecified", result);
            ArrayList<Contig> contigs = sequence.getReadingFrames();

            String[] columnNames = {"Position", "Frame", "Sequence"};

            Object[][] data = new Object[contigs.size()][3];
            int j = 0;
            for (int i = 0; i <= contigs.size() && j < 3; i++) {
                if (i == contigs.size()) {
                    j++;
                    i = -1;
                } else if (j == 0) {
                    data[i][j] = Integer.toString(contigs.get(i).getStartPosition());
                } else if (j == 1) {
                    data[i][j] = Integer.toString(contigs.get(i).getReadingFrame());
                } else if (j == 2) {
                    data[i][j] = contigs.get(i).getSequence();
                }
            }
            tableModel = new DefaultTableModel(data, columnNames);
        }
        return tableModel;
    }

    @Override
    protected void done() {
        try {
            TableModel model = get();
            if (model != null) {
                table.setModel(model);
            } else {
                // Handle possible null case...
            }
        } catch (InterruptedException | ExecutionException ex) {
            ex.printStackTrace();
        }
    }

}

返回构建TableModel

所需的数据
public class TableBuilder extends SwingWorker<Object[][], Void> {

    private JTable table;

    public TableBuilder(JTable table) {
        this.table = table;
    }

    @Override
    protected Object[][] doInBackground() throws Exception {
        Object[][] data = null;
        try (BufferedReader in = new BufferedReader(new FileReader(file))) {
            String line;
            String result = "";
            while ((line = in.readLine()) != null) {
                if (!line.startsWith(">")) {
                    result = result + line;
                }
            }

            Sequence sequence = new Sequence("Unspecified", result);
            ArrayList<Contig> contigs = sequence.getReadingFrames();

            data = new Object[contigs.size()][3];
            int j = 0;
            for (int i = 0; i <= contigs.size() && j < 3; i++) {
                if (i == contigs.size()) {
                    j++;
                    i = -1;
                } else if (j == 0) {
                    data[i][j] = Integer.toString(contigs.get(i).getStartPosition());
                } else if (j == 1) {
                    data[i][j] = Integer.toString(contigs.get(i).getReadingFrame());
                } else if (j == 2) {
                    data[i][j] = contigs.get(i).getSequence();
                }
            }
        }
        return data;
    }

    @Override
    protected void done() {
        try {
            Object[][] rows = get();
            if (rows != null) {
                String[] columnNames = {"Position", "Frame", "Sequence"};
                TableModel tableModel = new DefaultTableModel(data, columnNames);
                table.setModel(model);
            } else {
                // Handle possible null case...
            }
        } catch (InterruptedException | ExecutionException ex) {
            ex.printStackTrace();
        }
    }

}

答案 2 :(得分:1)

试试这个。由于缺少依赖性,源未经过测试。您只需要找到更新JTable的方法。我建议您使用CustomSwingWorker的实例创建TableModel,然后在方法中更新它:protected void done()

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import javax.sound.midi.Sequence;
import javax.swing.JTable;
import javax.swing.SwingWorker;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

public class CustomSwingWorker extends SwingWorker<TableModel, Void> {

    private File file;
    private JTable table;

    public CustomSwingWorker(final JTable table, final File file) {
        this.table = table;
        this.file = file;
    }

    @Override
    protected TableModel doInBackground() throws Exception {
        BufferedReader in = new BufferedReader(new FileReader(file));
        String line;
        String result = "";
        while ((line = in.readLine()) != null) {
            if (!line.startsWith(">")) {
                result = result + line;
            }
        }

        Sequence sequence = new Sequence("Unspecified", result);
        ArrayList<Contig> contigs = sequence.getReadingFrames();

        String [] columnNames = {"Position", "Frame", "Sequence"};

        Object[][] data = new Object[contigs.size()][3];
        int j = 0;
        for (int i = 0; i <= contigs.size() && j < 3; i++) {
            if (i == contigs.size()) {
                j++;
                i = -1;
            } else if (j == 0) {
                data[i][j] = Integer
                        .toString(contigs.get(i).getStartPosition());
            } else if (j == 1) {
                data[i][j] = Integer.toString(contigs.get(i).getReadingFrame());
            } else if (j == 2) {
                data[i][j] = contigs.get(i).getSequence();
            }
        }

        in.close();
        return new DefaultTableModel(data, columnNames);
    }

    protected void done() {
        try {
            this.table.setModel(this.get());
        } catch (Exception ignore) {
            // Simply ignore it ...
        }
    }
}