Swingworker producing duplicate output/output out of order?

Posted by Stefan Kendall on Stack Overflow See other posts from Stack Overflow or by Stefan Kendall
Published on 2010-04-25T00:48:07Z Indexed on 2010/04/25 0:53 UTC
Read the original article Hit count: 375

Filed under:
|
|
|

What is the proper way to guarantee delivery when using a SwingWorker? I'm trying to route data from an InputStream to a JTextArea, and I'm running my SwingWorker with the execute method. I think I'm following the example here, but I'm getting out of order results, duplicates, and general nonsense.

Here is my non-working SwingWorker:

class InputStreamOutputWorker extends SwingWorker<List<String>,String> {

    private InputStream is;
    private JTextArea output;

    public InputStreamOutputWorker(InputStream is, JTextArea output) {
        this.is = is;
        this.output = output;
    }

    @Override
    protected List<String> doInBackground() throws Exception {
        byte[] data = new byte[4 * 1024];
        int len = 0;

        while ((len = is.read(data)) > 0) {
            String line = new String(data).trim();
            publish(line);
        }

        return null;
    }

    @Override
    protected void process( List<String> chunks )
    {
        for( String s : chunks )
        {
            output.append(s + "\n");
        }
    }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about swingworker