gpt4 book ai didi

java - 将方法移动到 SwingWorker

转载 作者:行者123 更新时间:2023-11-29 07:46:25 25 4
gpt4 key购买 nike

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

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 中?我尝试了复制、粘贴和编辑,但整个过程只返回空结果。

最佳答案

我实际上有一个与“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
}
}
}

关于java - 将方法移动到 SwingWorker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25232718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com