Search code examples
javaswingswingworker

SwingWorker implementation error - abstract method not overridden


I am trying to wrap my brain around swing workers in general, but at the moment I am having difficulty even implementing them. I tried this in a separate class but got an error, but am still getting the error now that I have modeled it after some code I found online. The error I am getting is that it "is abstract and does not override abstract method doInBackground() in SwingWorker".

    SwingWorker zoomWorker = new SwingWorker() {
    @Override
    public Integer[] doInBackground(int quadrant, boolean zoomed) {

        Integer[] zoomData = new Integer[4];


    return zoomData;
    }


    };

Any help would be appreciated - I have read tons of tutorials but get lost in the rhetoric.


Solution

  • First write a concrete class extending SwingWorker so that the arguments can be passed in.

    Then

    Declare the first parameter type for the SwingWorker to match the return type of doInBackground. Use publish to notify the EDT of intermediate and completed results

     class MyWorker extends SwingWorker<Integer[], String> {
    
        private int quadrant;
        private boolean zoomed;
    
        public MyWorker(int quadrant, boolean zoomed) {
            this.quadrant = quadrant;
            this.zoomed = zoomed;
        }
    
        @Override
        protected Integer[] doInBackground() throws Exception {
            Integer[] zoomData = new Integer[4];
    
            // use quadrant && zoomData...
            publish("Intermediate data...");
            ...
    
            publish("complete");
            return zoomData;
        }
    };
    

    Read: Why do we need the SwingWorker?