Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8200693
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T06:32:12+00:00 2026-06-07T06:32:12+00:00

Please consider the following code fragment: import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.InvocationTargetException;

  • 0

Please consider the following code fragment:

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import javax.swing.*;

public class TestApplet extends JApplet
{
    @Override
    public void init()
    {
        try
        {
            SwingUtilities.invokeAndWait(new Runnable()
            {
                @Override
                public void run()
                {
                    createGUI();
                }
            });
        }
        catch(InterruptedException | InvocationTargetException ex)
        {
        }
    }

    private void createGUI()
    {
        getContentPane().setLayout(new FlowLayout());
        JButton startButton = new JButton("Do work");
        startButton.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent ae)
            {
                JLabel label = new JLabel();
                new Worker(label).execute();
            }
        });
        getContentPane().add(startButton);
    }

    private class Worker extends SwingWorker<Void, Void>
    {
        JLabel label;

        public Worker(JLabel label)
        {
            this.label = label;
        }

        @Override
        protected Void doInBackground() throws Exception
        {
            // do work
            return null;
        }

        @Override
        protected void done()
        {
            getContentPane().remove(label);
            getContentPane().revalidate();
        }
    }
}

Here is add a label to the applet that displays some intermediate results of the Worker thread (using publish/process methods). At the end, the label is removed from the applet’s pane. My question is, how could I create several labels, each with its own Worker thread, and remove them when they are all done?

Thanks in advance.

UPDATE:

I hope this will clarify my question. I’d like the labels to be removed all at once, when all of the workers have finished their tasks, not immediately after each worker has finished.

UPDATE 2:

The following code seems to be doing what I need. Please comment whether I did it the right way. I have a feeling there is something wrong. One problem is that the labels to the right of the button remain visible although they are removed. setVisible(false) seems to solve this issue. Is that the way to do it?

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.*;

public class TestApplet extends JApplet
{
    private Queue<JLabel> labels = new LinkedList<>();
    private static final Random rand = new Random();

    @Override
    public void init()
    {
        try
        {
            SwingUtilities.invokeAndWait(new Runnable()
            {
                @Override
                public void run()
                {
                    createGUI();
                }
            });
        }
        catch(InterruptedException | InvocationTargetException ex){}
    }

    private void createGUI()
    {
        getContentPane().setLayout(new FlowLayout());
        JButton startButton = new JButton("Do work");
        startButton.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent ae)
            {
                ExecutorService executor = Executors.newFixedThreadPool(10);
                for(int i = 0; i < 10; i++)
                {
                    JLabel label = new JLabel();
                    getContentPane().add(label);
                    executor.execute(new Counter(label));
                }
            }
        });
        getContentPane().add(startButton);
    }

    private class Counter extends SwingWorker<Void, Integer>
    {
        private JLabel label;

        public Counter(JLabel label)
        {
            this.label = label;
        }

        @Override
        protected Void doInBackground() throws Exception
        {
            for(int i = 1; i <= 100; i++)
            {
                publish(i);
                Thread.sleep(rand.nextInt(80));
            }

            return null;
        }

        @Override
        protected void process(List<Integer> values)
        {
            label.setText(values.get(values.size() - 1).toString());
        }

        @Override
        protected void done()
        {
            labels.add(label);

            if(labels.size() == 10)
            {
                while(!labels.isEmpty())
                    getContentPane().remove(labels.poll());

                getContentPane().revalidate();
            }
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T06:32:14+00:00Added an answer on June 7, 2026 at 6:32 am

    I intend to remove all of the labels together when all of the workers have completed their tasks.

    As described here, a CountDownLatch works well in this context. In the example below, each worker invokes latch.countDown() on completion, and a Supervisor worker blocks on latch.await() until all tasks complete. For demonstration purposes, the Supervisor updates the labels. Wholesale removal, shown in comments, is technically possible but generally unappealing. Instead, consider a JList or JTable.

    Worker Latch Test

    import java.awt.Color;
    import java.awt.EventQueue;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Queue;
    import java.util.Random;
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import javax.swing.*;
    
    /**
    * @see https://stackoverflow.com/a/11372932/230513
    * @see https://stackoverflow.com/a/3588523/230513
    */
    public class WorkerLatchTest extends JApplet {
    
        private static final int N = 8;
        private static final Random rand = new Random();
        private Queue<JLabel> labels = new LinkedList<JLabel>();
        private JPanel panel = new JPanel(new GridLayout(0, 1));
        private JButton startButton = new JButton(new StartAction("Do work"));
    
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    JFrame frame = new JFrame();
                    frame.setTitle("Test");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new WorkerLatchTest().createGUI());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        @Override
        public void init() {
            EventQueue.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    add(new WorkerLatchTest().createGUI());
                }
            });
        }
    
        private JPanel createGUI() {
            for (int i = 0; i < N; i++) {
                JLabel label = new JLabel("0", JLabel.CENTER);
                label.setOpaque(true);
                panel.add(label);
                labels.add(label);
            }
            panel.add(startButton);
            return panel;
        }
    
        private class StartAction extends AbstractAction {
    
            private StartAction(String name) {
                super(name);
            }
    
            @Override
            public void actionPerformed(ActionEvent e) {
                    startButton.setEnabled(false);
                    CountDownLatch latch = new CountDownLatch(N);
                    ExecutorService executor = Executors.newFixedThreadPool(N);
                    for (JLabel label : labels) {
                        label.setBackground(Color.white);
                        executor.execute(new Counter(label, latch));
                    }
                    new Supervisor(latch).execute();
            }
        }
    
        private class Supervisor extends SwingWorker<Void, Void> {
    
            CountDownLatch latch;
    
            public Supervisor(CountDownLatch latch) {
                this.latch = latch;
            }
    
            @Override
            protected Void doInBackground() throws Exception {
                latch.await();
                return null;
            }
    
            @Override
            protected void done() {
                for (JLabel label : labels) {
                    label.setText("Fin!");
                    label.setBackground(Color.lightGray);
                }
                startButton.setEnabled(true);
                //panel.removeAll(); panel.revalidate(); panel.repaint();
            }
        }
    
        private static class Counter extends SwingWorker<Void, Integer> {
    
            private JLabel label;
            CountDownLatch latch;
    
            public Counter(JLabel label, CountDownLatch latch) {
                this.label = label;
                this.latch = latch;
            }
    
            @Override
            protected Void doInBackground() throws Exception {
                int latency = rand.nextInt(42) + 10;
                for (int i = 1; i <= 100; i++) {
                    publish(i);
                    Thread.sleep(latency);
                }
                return null;
            }
    
            @Override
            protected void process(List<Integer> values) {
                label.setText(values.get(values.size() - 1).toString());
            }
    
            @Override
            protected void done() {
                label.setBackground(Color.green);
                latch.countDown();
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Please consider following code: 1. uint16 a = 0x0001; if(a < 0x0002) { //
Please consider the following code: mpz_t x, n, out; mpz_init_set_ui(x, 2UL); mpz_init_set_ui(n, 7UL); mpz_init(out);
Please consider the following code: public class Person ( public string FirstName {get; set;}
Please consider the following code, struct foo { foo() { std::cout << Constructing! <<
Please consider the following example code (from the lm doc): ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14) trt
Please consider the following java source: package com.stackoverflow; public class CondSpeed { private static
Please consider the following code: #include <iostream> #include <typeinfo> template< typename Type > void
Please consider the following code, <form action=index.php method=post name=adminForm enctype=multipart/form-data> <input type=hidden name=showtime[] id=showtime_1
Please consider the following code: class Abase{}; class A1:public Abase{}; class A2:public A1{}; //etc
please consider the following code: template <typename T> struct foo { template <typename S>

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.