我試圖讓JTextArea
這個名爲textArea
的圖片在它複製這些照片時進行更新,但我似乎無法完成它的工作。我用這個代碼:需要在JTextArea中實時更新
String name = "";
int numberOfPicturesCopied = 0;
while (pictures.isEmpty() == f) {
try {
File tmp = pictures.firstElement();
name = tmp.getName();
String filename = destination + Meta.date(tmp) + tmp.getName();
Path source = tmp.toPath();
File destFile = new File(filename);
Path destination = destFile.toPath();
Files.copy(source, destination,
StandardCopyOption.COPY_ATTRIBUTES);
textArea.append("Copied " + name + "\n");
pictures.removeElementAt(0);
numberOfPicturesCopied++;
} catch (FileAlreadyExistsException faee) {
textArea.append("Skipped " + name
+ ": Picture Already In Computer\n");
} catch (NoSuchFileException ncfe) {
File tmp = pictures.firstElement();
String filename = destination + Meta.date(tmp);
File newDir = new File(filename);
newDir.mkdir();
} catch (IOException ee) {
// TODO Auto-generated catch block
ee.printStackTrace();
}
}
,然後我把它改成這樣:
public void copyPictures(){
SwingUtilities.invokeLater(new Thread(){
public void run(){
String name = "";
while(pictures.isEmpty() == f){
try {
File tmp = pictures.firstElement();
name = tmp.getName();
String filename = destination + Meta.date(tmp) + tmp.getName();
Path source = tmp.toPath();
File destFile = new File(filename);
Path destination = destFile.toPath();
Files.copy(source, destination, StandardCopyOption.COPY_ATTRIBUTES);
textArea.append("Copied " + name + "\n");
pictures.removeElementAt(0);
numberOfPicturesCopied++;
} catch(FileAlreadyExistsException faee){
textArea.append("Skipped " + name +": Picture Already In Computer\n");
} catch (NoSuchFileException ncfe){
File tmp = pictures.firstElement();
String filename = destination + Meta.date(tmp);
File newDir = new File(filename);
newDir.mkdir();
} catch (IOException ee) {
// TODO Auto-generated catch block
ee.printStackTrace();
}
}
}
});
}
具有相同的結果。有什麼建議麼?
此外,有什麼辦法讓文本進入文本區域的頂部?
1)爲了更好的幫助,請儘快發佈[SSCCE]( http://sscce.org/)你最好的嘗試。你嘗試過的其他東西可以用(例如)'copyPictures2()'方法表示。 2)看來你阻止了美國東部時間。使用'SwingWorker'。 –
'SwingUtilities.invokeLater(new Thread())'是平坦的錯誤。您需要乾淨地分離您在後臺線程上執行的文件I/O工作與Swing組件的更新,這些工作應該在EDT上完成。 – wolfcastle