FirmView
FirmView

Reputation: 3150

Implementing SwingWorker

Thought of making a small textEditor. It will contain two textareas, one for entering the text and one for error display. As for my understanding, SwingWorker works in background so there will be no delay in the UI updation. For checking, i wrote the below code and inserted 5000 lines and tried to type, i think as the line goes on increasing, the updation in textEditor2 is becoming very slow. Is the implementation of the swingworker is correct in the code?

textEditor1 and textEditor2 are JTextarea

 private void editorKeyPressed(java.awt.event.KeyEvent evt) {

SwingWorker worker = new SwingWorker<Void, Void>() {
    String text = null;

    @Override
    protected Void doInBackground() throws Exception {
        text = textEditor1.getText().toString();
        return null;
    }

    @Override
    protected void done() {
        try {
            get();
            textEditor2.setText(text);
        } catch (Exception ex) {
            System.out.println(ex);
        }
    }
};

worker.execute();   
}

Upvotes: 1

Views: 1197

Answers (2)

John
John

Reputation: 196

You are spawning worker threads every time the key is pressed, I expect that's why you're seeing the degradation in performance.

You still need to manage the number of threads you're executing to maintain UI responsiveness. If you want your background task to always be running, setup your own thread and use a class from the concurrent package to fascilitate passing data off of the Event thread (e.g. ArrayBlockingQueue).

Upvotes: 3

Balconsky
Balconsky

Reputation: 2244

For this task you should not use SwingWorker. Just do It in one thread.

private void editorKeyPressed(java.awt.event.KeyEvent evt) {
text = textEditor1.getText();
textEditor2.setText(text);
}

Upvotes: 0

Related Questions