如何在Java中自动添加行时,如何在TextArea上进行自动滚动

时间:2014-03-14 07:29:45

标签: java swing file-io jtextarea autoscroll

我在Java中有一个对话窗口,它自动复制一些文件,并有一个TextArea,显示我复制了哪个文件,ProgressBar女巫向我显示百分比。 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仅在副本结束时更新

1 个答案:

答案 0 :(得分:1)

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

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