如何在Java中自动添加行时使文本区域自动滚动

如何在Java中自动添加行时使文本区域自动滚动,java,swing,file-io,jtextarea,autoscroll,Java,Swing,File Io,Jtextarea,Autoscroll,我在Java中有一个对话框窗口,可以自动复制一些文件,有一个文本区域,显示复制了哪个文件,还有一个进度条,显示百分比。ProgressBar工作正常。我有问题的TextArea,我想当一行添加,TextArea自动向下滚动。 我的代码是: public void copyDirectory(File sourceLocation, File targetLocation) { this.sourceLocation = sourceLocation; this.targetL

我在Java中有一个对话框窗口,可以自动复制一些文件,有一个文本区域,显示复制了哪个文件,还有一个进度条,显示百分比。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仅在复制结束时更新

将滚动窗格与文本区域一起使用:

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);

我不相信AutoScrolls酒店能满足您的期望。至少,如果您希望这将使框自行滚动,我认为您需要将
JTextArea
放置在
JScrollPane
中,以产生任何滚动效果。你这样做了吗?这只有通过将FileIO重定向到WorkerThread才能实现,更详细的阅读请参见官方Oracle教程中的Concurence in Swingremember,将滚动窗格也添加到窗口的框架中。我已经添加了它。谢谢
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);