我为我的游戏制作了一个小型启动器,我试图让它下载一些文件。一切都有效,除了进度条和它上面的JLabel。他们下载时不会更新。以下是我的一些代码:
static void checkForUpdates() {
Gui.progressBar.setIndeterminate(true);
Gui.status.setText("Status: Checking for cache updates...");
try {
double newest = getNewestVersion();
double current = getCurrentVersion();
if(newest > current) {
downloadCache();
unzipCache();
setLatestCacheVersion(newest);
}
} catch(Exception e) {
e.printStackTrace();
}
}
private static void downloadCache() throws IOException {
Gui.progressBar.setIndeterminate(false);
URL url = new URL(Configuration.CACHE_URL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.addRequestProperty("User-Agent", "Mozilla/4.76");
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = Configuration.CACHE_NAME;
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = Configuration.SAVE_DIRECTORY + fileName;
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[4096];
long numWritten = 0;
int length = httpConn.getContentLength();
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
numWritten += bytesRead;
int percentage = (int)(((double)numWritten / (double)length) * 100D);
Gui.progressBar.setValue(percentage);
Gui.progressBar.repaint();
}
outputStream.close();
inputStream.close();
} else {
System.out.println("Cache host replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}
它一直在说:检查更新,因为这是我在开始时设置的内容,但在此之后它不会更新。
static JLabel status = new JLabel("Checking for updates...", SwingConstants.CENTER);
我做了一些研究,我发现如果我没有弄错的话,我必须和swingworker做点什么。问题是我不知道在这种情况下我会怎么做。