views:

30

answers:

1

I am trying to append a percentage to a text area in java. It involves a loop that determines the percentage and then appends that to another JFrame with the text area in it.

The "pro" class simply has a window with a JtextArea.

The problem that I am encountering is that the window appears to show the window underneath, as if it were lagging. Is there anyway of fixing this. I have tried looking at SwingWorker but I am finding it confusing. Any help would be greatly appreciated. Below is an extract of the program.

thanks.

public void copy(File sourceLocation, File targetLocation) throws IOException {

  if (sourceLocation.isDirectory()) {
        if (!targetLocation.exists()) {
            targetLocation.mkdir();
        }

        String[] children = sourceLocation.list();
        for (int i=0; i<children.length; i++) {

            int length = children.length - 1;

            float percentage = (i/(float)length) *100;
            String d = percentage + "%" + " " + sourceLocation;
            System.out.println(percentage + "%" + " " + sourceLocation);

            pro.area.append(percentage + "\n");




            copy(new File(sourceLocation, children[i]),
                    new File(targetLocation, children[i]));
        }
    } else {

        InputStream in = new FileInputStream(sourceLocation);
        OutputStream out = new FileOutputStream(targetLocation);

        // Copy the bits from instream to outstream
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
        //pro.setVisible(false);
    }

}

+1  A: 

The graphical anomaly is likely due to blocking the event dispatch thread. SwingWorker is the preferred approach; but using continuations as objects is an alternative, as shown here.

trashgod