Question

i have 2 class. One for GUI, and anther for reading file with updating it, to the JTable ,but it take long time. I would like to use SwingWorker to fix the issue. i found tutorials like this one SwingWorker, but still i don't get it. where do i have to use SwingWorker; is it in the reading class or GUI class, i never ever try it and i don't know any thing about it; I tried to google every where, buti need very simple example "the simplest) in other word where to start

Was it helpful?

Solution

Here is a minimal example. It is a program displaying a dummy progress in a JLabel :

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;


public class GUI extends JFrame {

    private JLabel lblProgress = new JLabel("0%");

    public GUI() {
       setTitle("Swing worker example");
       setSize(300, 200);    
       add(lblProgress);
       new Process().execute();
    }


    public static void main(String[] args) {
       SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                GUI gui = new GUI();
                gui.setVisible(true);
            }
        });
    }

    class Process extends SwingWorker<String, String> {

        @Override
        protected String doInBackground() throws InterruptedException {
            int count = 10000;
            for (int i = 0; i < count; i++) {
                int progress = (int) ((double) i/count*100.0);
                lblProgress.setText(progress + "%");
                repaint();
                Thread.sleep(10);
            }
            return null;
        }

        @Override
        protected void done() {
            lblProgress.setText("Finished!");
        }
     }

 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top