0

I'm trying to override the process() method to ensure that some code runs in the EDT. I have made sure that <T,V> are matching throughout but it still won't let me override. Here is my code:

final SwingWorker<ArrayList<Block>,Integer[]> swingSlaveLabourer = new SwingWorker<ArrayList<Block>, Integer[]>() {

    @Override 
    protected ArrayList<Block> doInBackground() throws Exception {
        blockList.doHeavyWork()..
        Integer [] status = new Integer[2];
        status[0] = 1;
        status[1] = 0;
        this.process(status);
        return blockList;
    }

    @Override //wont allow override
    protected void process (Integer[] chunks){
        progressBar.setValue(chunks[0]);
    }
};
Tunaki
  • 132,869
  • 46
  • 340
  • 423
OrangePot
  • 1,053
  • 2
  • 14
  • 38

1 Answers1

2

The process method takes a List<V> as argument. It represents all the data chunks that were published. You need to change your code to:

@Override
protected void process(List<Integer[]> chunks) {
    // do something
}

You should not call directly process from the doInBackground method. Instead, you should call publish to publish each chunk of data.

Refer to the following example taken from the SwingWorker Javadoc:

class PrimeNumbersTask extends SwingWorker<List<Integer>, Integer> {

     PrimeNumbersTask(JTextArea textArea, int numbersToFind) {
         //initialize
     }

     @Override
     public List<Integer> doInBackground() {
         while (! enough && ! isCancelled()) {
                 number = nextPrimeNumber();
                 publish(number); // each computed number is published
                 setProgress(100 * numbers.size() / numbersToFind); // and progress updated
             }
         }
         return numbers;
     }

     @Override
     protected void process(List<Integer> chunks) {
         // in the mean while, we print each published value to a textarea
         for (int number : chunks) {
             textArea.append(number + "\n");
         }
     }
 }
Tunaki
  • 132,869
  • 46
  • 340
  • 423
  • So im passing an arrayList of arrays of Integers? chunks.get(0)[0] seems a little strange. Will that list ever contain more that one element? i feel as though i will always be using chunks.get(0). Isnt that a little redundant? An integer array wouldnt suffice? – OrangePot Sep 30 '15 at 17:54
  • @OrangePot Your design is not correct. See the example I posted. – Tunaki Sep 30 '15 at 17:55
  • So the point of `doInBackground()` is to do heavy work, why is it changing a GUI component (`setProgress()`)? – OrangePot Sep 30 '15 at 18:00
  • @OrangePot It is not changing a GUI component, it is simply updating the progress variable. GUI component should be updated in the EDT, i.e. inside the process method. [See this answer](http://stackoverflow.com/a/20270356/1743880) for the difference between background thread and EDT. – Tunaki Sep 30 '15 at 18:04