【发布时间】:2014-03-14 07:29:45
【问题描述】:
我在 Java 中有一个对话框窗口,它会自动复制一些文件,并有一个 TextArea 可以告诉我哪个文件被复制了,而 ProgressBar 女巫会告诉我百分比。 ProgressBar 运行良好。我对 TextArea 有问题,我希望在添加一行时,TextArea 自动向下滚动。
我的代码是:
public void copyDirectory(File sourceLocation, File targetLocation) {
this.sourceLocation = sourceLocation;
this.targetLocation = targetLocation;
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists()) {
targetLocation.mkdir();
}
String[] children = sourceLocation.list();
for (int i = 0; i < children.length; i++) {
try {
Thread.sleep(100);//
} catch (Exception e) {
e.printStackTrace();
}
jTextArea1.append("100% : Copy... " + children[i] + "\n");
jTextArea1.setCaretPosition(jTextArea1.getDocument().getLength());
jTextArea1.repaint();
jTextArea1.setAutoscrolls(true);
jTextArea1.update(jTextArea1.getGraphics());
jScrollPane1.repaint();
jScrollPane1.update(jScrollPane1.getGraphics());
countFile++;
pos += 1;
jProgressBar1.setValue(15 + (countFile * 75) / (a));
jProgressBar1.repaint();
jProgressBar1.update(jProgressBar1.getGraphics());
copyDirectory(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
try {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (IOException e) {
}
}
}
我已经添加了 jTextArea1 的代码:
jTextArea1 = new javax.swing.JTextArea();
DefaultCaret caret = (DefaultCaret)jTextArea1.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
jTextArea1 仅在复制结束时更新
【问题讨论】:
-
我不相信 AutoScrolls 属性会满足您的期望。至少如果您希望这会使框自行滚动
-
我认为您需要将
JTextArea放在JScrollPane中才能产生滚动效果。你这样做吗? -
这只能通过将 FileIO 重定向到 WorkerThread 来实现,更多请阅读官方 Oracle 教程 Concurency in Swing
标签: java swing file-io jtextarea autoscroll