我創建了一個彈出窗口來顯示某些東西的進度,並且它與我的下載程序正常工作,所有內容都正在更新。JProgressBar在一個線程上更新,而不是在另一個線程上更新
private void downloadFile(String link, String directory, String name) throws IOException {
task = new Downloader(link, directory, name);
task.start();
}
,並在下載類:
public void run() {
try {
while ((length = is.read(b)) != -1) {
downloaded += length;
bout.write(b, 0, length);
int percent = (int) ((downloaded * 100)/fileLength);
window.modify1("Downloading " + name + ".jar");
window.modify2((int) downloaded, "Progress: " + percent + "% [" + String.valueOf(downloaded).subSequence(0, String.valueOf(downloaded).length() - 1) + "kb/" + String.valueOf(fileLength).subSequence(0, String.valueOf(fileLength).length() - 1) + "kb]");
}
is.close();
bout.close();
window.exit();
Creator c = new Creator(directory, name);
c.create();
this.join();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
然而,當我試圖在另一個線程做的差不多了,這是行不通的。直到線程完成後才顯示彈出窗口中的任何內容。
LauncherThread t = new LauncherThread();
t.start();
try {
t.join();
} catch (InterruptedException e2) {
e2.printStackTrace();
}
,並在LauncherThread類:
public void run() {
window.modify1("Fetching data...");
window.modify2(0, "Progress: 0% [0/10]");
Main.trust();
window.modify2(1, "Progress: 10% [1/10]");
Main.bukkitVersions = Finder.findBukkitVersions();
window.modify2(2, "Progress: 20% [2/10]");
Main.spigotVersions = Finder.findSpigotVersions();
window.modify2(3, "Progress: 30% [3/10]");
Main.vanillaVersion = Finder.findVanillaVersion();
window.modify2(4, "Progress: 40% [4/10]");
Main.bukkitLinks = new String[3];
Main.bukkitLinks[0] = Finder.findDownloadLink("bukkit", "rb");
window.modify2(5, "Progress: 50% [5/10]");
Main.bukkitLinks[1] = Finder.findDownloadLink("bukkit", "beta");
window.modify2(6, "Progress: 60% [6/10]");
Main.bukkitLinks[2] = Finder.findDownloadLink("bukkit", "dev");
window.modify2(7, "Progress: 70% [7/10]");
Main.spigotLinks = new String[2];
Main.spigotLinks[0] = Finder.findDownloadLink("spigot", "lastStable");
window.modify2(8, "Progress: 80% [8/10]");
Main.spigotLinks[1] = Finder.findDownloadLink("spigot", "lastBuild");
window.modify2(9, "Progress: 90% [9/10]");
Main.vanillaLink = Finder.findDownloadLink("vanilla", null);
window.modify2(10, "Progress: 100% [10/10]");
window.exit();
}
我還是很新的Java的,所以我爲我的無知道歉。
編輯:我在SwingUtilities.invokeLater()中封裝了t.start()方法,現在它可以工作。但新問題是主類不再等待LauncherThread完成。