gpt4 book ai didi

java - 如何在Java中自动添加行时在TextArea上自动滚动

转载 作者:行者123 更新时间:2023-12-01 13:16:53 25 4
gpt4 key购买 nike

我在Java中有一个对话框窗口,它自动复制一些文件,并且有一个TextArea显示哪个文件被复制,一个ProgressBar女巫显示百分比。进度条工作完美。我对 TextArea 有问题,我希望添加一行时,TextArea 自动向下滚动。 enter image description here

我的代码是:

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 仅在复制结束时更新

最佳答案

在文本区域中使用滚动 Pane :

JScrollPane txt_more_info_pane = new JScrollPane(jTextArea);  
txt_more_info_pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
txt_more_info_pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

关于java - 如何在Java中自动添加行时在TextArea上自动滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22398710/

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