Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #17453 > unrolled thread

Can you get this SwingWorker code to work more than once

Started byclusardi2k@aol.com
First post2012-08-09 08:24 -0700
Last post2012-08-09 09:18 -0700
Articles 8 — 4 participants

Back to article view | Back to comp.lang.java.programmer


Contents

  Can you get this SwingWorker code to work more than once clusardi2k@aol.com - 2012-08-09 08:24 -0700
    Re: Can you get this SwingWorker code to work more than once Eric Sosman <esosman@ieee-dot-org.invalid> - 2012-08-09 11:48 -0400
      Re: Can you get this SwingWorker code to work more than once clusardi2k@aol.com - 2012-08-09 08:55 -0700
        Re: Can you get this SwingWorker code to work more than once markspace <-@.> - 2012-08-09 09:11 -0700
        Re: Can you get this SwingWorker code to work more than once Eric Sosman <esosman@ieee-dot-org.invalid> - 2012-08-09 14:29 -0400
      Re: Can you get this SwingWorker code to work more than once clusardi2k@aol.com - 2012-08-09 09:11 -0700
        Re: Can you get this SwingWorker code to work more than once Eric Sosman <esosman@ieee-dot-org.invalid> - 2012-08-09 14:31 -0400
    Re: Can you get this SwingWorker code to work more than once Knute Johnson <nospam@knutejohnson.com> - 2012-08-09 09:18 -0700

#17453 — Can you get this SwingWorker code to work more than once

Fromclusardi2k@aol.com
Date2012-08-09 08:24 -0700
SubjectCan you get this SwingWorker code to work more than once
Message-ID<d88d5a10-6b44-4917-9bc3-dee0b5d745f1@googlegroups.com>
Here is a project that works perfectly only the first time. This is what it does on the first button press:

It starts-up with only a "Start" button.

(1) Pressing start displays "Hello World".
(2) The three "for" loops are executed in the code.
(3) "Hello World" disappears.

But, when you press the "Start" button a second time this happens:

(1) Displays "Hello World",

How do you modify the below code so that the second button press matches the first button press.

The code has a button and a label.

After answering the above question, another question that I have is: can you make this code better in any way imaginable.

Thank you,

//Code:
package Test_SwingWorker;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;
import javax.swing.SwingWorker;

public class Test_SwingWorker extends javax.swing.JFrame 
{
    public Test_SwingWorker() 
    {
        initComponents();

        //The "Hello World" label that is not seen on Start-up
        jLabel1.setVisible (false);
        
        final Non_GUI_Stuff task = new Non_GUI_Stuff();  
        
        jButton1.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent e)
            {
                //The "Hello World" label that appears when button is pressed
                jLabel1.setVisible (true);
        
                task.execute(); 
            } 
         }); 
    }
                      
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Start");

        jLabel1.setText("Hello World");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(167, 167, 167)
                .addComponent(jButton1)
                .addGap(51, 51, 51)
                .addComponent(jLabel1)
                .addContainerGap(55, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)))
                .addContainerGap(283, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }                      

    public static void main(String args[]) 
    {
        java.awt.EventQueue.invokeLater(new Runnable() 
        {
            public void run() 
            {
                new Test_SwingWorker().setVisible(true);
            }
        });
    }
    
class Non_GUI_Stuff extends SwingWorker<Integer, Integer> 
{ 
  protected Integer doInBackground() throws Exception 
  {
      //"for" loops mentioned above
      for (int i = 0;i < 100000; i++)
          for (int i2 = 0;i2 < 100000; i2++);
      for (int i3 = 0;i3 < 100000; i3++);
                 
    return 0;
  } 
   
  protected void done() 
  {
      //The "Hello World" label that disappears
      jLabel1.setVisible (false);
  } 
}     
                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;                 
}

[toc] | [next] | [standalone]


#17455

FromEric Sosman <esosman@ieee-dot-org.invalid>
Date2012-08-09 11:48 -0400
Message-ID<k00m3o$uos$1@dont-email.me>
In reply to#17453
On 8/9/2012 11:24 AM, clusardi2k@aol.com wrote:
> Here is a project that works perfectly only the first time.  [...]

     Quoth the JavaDoc: "SwingWorker is only designed to be executed
once. Executing a SwingWorker more than once will not result in
invoking the doInBackground method twice."  If you want to do a
background task N times, you'll need N instances of SwingWorker,
one per task execution.

-- 
Eric Sosman
esosman@ieee-dot-org.invalid

[toc] | [prev] | [next] | [standalone]


#17456

Fromclusardi2k@aol.com
Date2012-08-09 08:55 -0700
Message-ID<4cc76fc2-fffc-470d-b4c6-0be778070523@googlegroups.com>
In reply to#17455
On Thursday, August 9, 2012 11:48:04 AM UTC-4, Eric Sosman wrote:
> On 8/9/2012 11:24 AM, ... wrote: > Here is a project that works 
> perfectly only the first time. [...] Quoth the JavaDoc: "SwingWorker is only 
> designed to be executed once. Executing a SwingWorker more than once will not 
> result in invoking the doInBackground method twice." If you want to do a 
> background task N times, you'll need N instances of SwingWorker, one per task 
> execution. -- Eric Sosman esosman@ieee-dot-org.invalid

So, I want a project to do the following: 

(1) Display a button when the project is run,
(2) When the user presses the button, a label is displayed.
(3) The project next executes three long "for" loops such as in a previous post of this thread.
(4) When the three "for" loops are finished, the label disappears.

Question: How can I repeatedly do steps (2) through (4) above when a project is started?

Thank you,

[toc] | [prev] | [next] | [standalone]


#17458

Frommarkspace <-@.>
Date2012-08-09 09:11 -0700
Message-ID<k00nfs$8b7$1@dont-email.me>
In reply to#17456
On 8/9/2012 8:55 AM, clusardi2k@aol.com wrote:

> On Thursday, August 9, 2012 11:48:04 AM UTC-4, Eric Sosman wrote:
>> On 8/9/2012 11:24 AM, ... wrote: > Here is a project that works
>> perfectly only the first time. [...] Quoth the JavaDoc: "SwingWorker is only
>> designed to be executed once. Executing a SwingWorker more than once will not
>> result in invoking the doInBackground method twice." If you want to do a
>> background task N times, you'll need N instances of SwingWorker, one per task
>> execution. -- Eric Sosman esosman@ieee-dot-org.invalid

>
> So, I want a project to do the following:
>
> (1) Display a button when the project is run,
> (2) When the user presses the button, a label is displayed.
> (3) The project next executes three long "for" loops such as in a previous post of this thread.
> (4) When the three "for" loops are finished, the label disappears.
>
> Question: How can I repeatedly do steps (2) through (4) above when a project is started?


In this case just move the "new Non_GUI_Stuff()" inside the 
actionPreformed() method.  Then "new" will get executed each time the 
user presses the button, you'll get a new object that you can execute 
with no problems.


     jButton1.addActionListener(new ActionListener()
     {
         public void actionPerformed(ActionEvent e)
         {
             //The "Hello World" label that appears
             //when button is pressed

             Non_GUI_Stuff task = new Non_GUI_Stuff();

             jLabel1.setVisible (true);

             task.execute();
         }
      });


If all you really want to do is delay the label disappearing, use a 
Timer instead of for-loops.

[toc] | [prev] | [next] | [standalone]


#17462

FromEric Sosman <esosman@ieee-dot-org.invalid>
Date2012-08-09 14:29 -0400
Message-ID<k00vii$voo$1@dont-email.me>
In reply to#17456
On 8/9/2012 11:55 AM, clusardi2k@aol.com wrote:
> On Thursday, August 9, 2012 11:48:04 AM UTC-4, Eric Sosman wrote:
>> On 8/9/2012 11:24 AM, ... wrote: > Here is a project that works
>> perfectly only the first time. [...] Quoth the JavaDoc: "SwingWorker is only
>> designed to be executed once. Executing a SwingWorker more than once will not
>> result in invoking the doInBackground method twice." If you want to do a
>> background task N times, you'll need N instances of SwingWorker, one per task
>> execution. -- Eric Sosman esosman@ieee-dot-org.invalid
>
> So, I want a project to do the following:
>
> (1) Display a button when the project is run,
> (2) When the user presses the button, a label is displayed.
> (3) The project next executes three long "for" loops such as in a previous post of this thread.
> (4) When the three "for" loops are finished, the label disappears.
>
> Question: How can I repeatedly do steps (2) through (4) above when a project is started?

     "When a project is started?"  Or "Each time the user presses
the button?"  I'll assume the latter.

     When you set up the button, create an ActionListener to be
notified of button presses.  The listener's actionPerformed()
method will display the label (that's #2 above), create a SwingWorker,
call the worker's execute() method, and return.

     Because execute() was called, Java will ("eventually," but in
practice "fairly soon") start the SwingWorker on a background
thread and call its doInBackground() method.  This method runs the
long loops (#3) and then returns.  Note that since it's executing
on a background thread and not on the event dispatch thread (EDT),
doInBackground() should do almost nothing to or with the GUI: Only
a very few bits of Swing are thread-safe.

     After doInBackground() returns, Java will ("eventually/soon")
call the SwingWorker's done() method.  This call runs on the EDT,
so the done() method can manipulate the GUI: It can make the label
invisible or even remove it from its container (#4).

     Next time the user presses the button, the actionPerformed()
method creates a brand-new SwingWorker and the same sequence of
actions repeats.  You can't re-use the old SwingWorker instance,
but you can create a new instance of the same class, running the
same code.

     All this and more is covered in the Java Tutorial's chapter
on Swing concurrency,

<http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html>

-- 
Eric Sosman
esosman@ieee-dot-org.invalid

[toc] | [prev] | [next] | [standalone]


#17457

Fromclusardi2k@aol.com
Date2012-08-09 09:11 -0700
Message-ID<4e08dd61-cd74-4ec1-b568-aef1645d3758@googlegroups.com>
In reply to#17455
On Thursday, August 9, 2012 11:48:04 AM UTC-4, Eric Sosman wrote:
> On 8/9/2012 11:24 AM, clusardi2k@aol.com wrote: > Here is a project that works 
> perfectly only the first time. [...] Quoth the JavaDoc: "SwingWorker is only 
> designed to be executed once. Executing a SwingWorker more than once will not 
> result in invoking the doInBackground method twice." If you want to do a 
> background task N times, you'll need N instances of SwingWorker, one per task 
> execution. -- Eric Sosman esosman@ieee-dot-org.invalid

How do you modify the code my last post to do that.

Thank you,

[toc] | [prev] | [next] | [standalone]


#17463

FromEric Sosman <esosman@ieee-dot-org.invalid>
Date2012-08-09 14:31 -0400
Message-ID<k00vme$voo$2@dont-email.me>
In reply to#17457
On 8/9/2012 12:11 PM, clusardi2k@aol.com wrote:
> On Thursday, August 9, 2012 11:48:04 AM UTC-4, Eric Sosman wrote:
>> On 8/9/2012 11:24 AM, clusardi2k@aol.com wrote: > Here is a project that works
>> perfectly only the first time. [...] Quoth the JavaDoc: "SwingWorker is only
>> designed to be executed once. Executing a SwingWorker more than once will not
>> result in invoking the doInBackground method twice." If you want to do a
>> background task N times, you'll need N instances of SwingWorker, one per task
>> execution. -- Eric Sosman esosman@ieee-dot-org.invalid
>
> How do you modify the code my last post to do that.

     Because there's a faint whiff of "homework assignment" about
your questions, *I* don't modify your code at all.  *You* modify
it along the lines people have suggested, and post your new code
if you're still having trouble with it.

-- 
Eric Sosman
esosman@ieee-dot-org.invalid

[toc] | [prev] | [next] | [standalone]


#17460

FromKnute Johnson <nospam@knutejohnson.com>
Date2012-08-09 09:18 -0700
Message-ID<k00nsg$aj2$1@dont-email.me>
In reply to#17453
On 8/9/2012 8:24 AM, clusardi2k@aol.com wrote:
> Here is a project that works perfectly only the first time. This is what it does on the first button press:
>
> It starts-up with only a "Start" button.
>
> (1) Pressing start displays "Hello World".
> (2) The three "for" loops are executed in the code.
> (3) "Hello World" disappears.
>
> But, when you press the "Start" button a second time this happens:
>
> (1) Displays "Hello World",
>
> How do you modify the below code so that the second button press matches the first button press.
>
> The code has a button and a label.
>
> After answering the above question, another question that I have is: can you make this code better in any way imaginable.
>
> Thank you,
>
> //Code:
> package Test_SwingWorker;
>
> import java.awt.event.ActionEvent;
> import java.awt.event.ActionListener;
> import java.beans.PropertyChangeEvent;
> import java.beans.PropertyChangeListener;
> import java.util.List;
> import javax.swing.SwingWorker;
>
> public class Test_SwingWorker extends javax.swing.JFrame
> {
>      public Test_SwingWorker()
>      {
>          initComponents();
>
>          //The "Hello World" label that is not seen on Start-up
>          jLabel1.setVisible (false);
>
>          final Non_GUI_Stuff task = new Non_GUI_Stuff();
>
>          jButton1.addActionListener(new ActionListener()
>          {
>              public void actionPerformed(ActionEvent e)
>              {
>                  //The "Hello World" label that appears when button is pressed
>                  jLabel1.setVisible (true);
>
>                  task.execute();
>              }
>           });
>      }
>
>      private void initComponents() {
>
>          jPanel1 = new javax.swing.JPanel();
>          jButton1 = new javax.swing.JButton();
>          jLabel1 = new javax.swing.JLabel();
>
>          setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
>
>          jButton1.setText("Start");
>
>          jLabel1.setText("Hello World");
>
>          javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
>          jPanel1.setLayout(jPanel1Layout);
>          jPanel1Layout.setHorizontalGroup(
>              jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
>              .addGroup(jPanel1Layout.createSequentialGroup()
>                  .addGap(167, 167, 167)
>                  .addComponent(jButton1)
>                  .addGap(51, 51, 51)
>                  .addComponent(jLabel1)
>                  .addContainerGap(55, Short.MAX_VALUE))
>          );
>          jPanel1Layout.setVerticalGroup(
>              jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
>              .addGroup(jPanel1Layout.createSequentialGroup()
>                  .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
>                      .addComponent(jButton1)
>                      .addGroup(jPanel1Layout.createSequentialGroup()
>                          .addContainerGap()
>                          .addComponent(jLabel1)))
>                  .addContainerGap(283, Short.MAX_VALUE))
>          );
>
>          javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
>          getContentPane().setLayout(layout);
>          layout.setHorizontalGroup(
>              layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
>              .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
>          );
>          layout.setVerticalGroup(
>              layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
>              .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
>          );
>
>          pack();
>      }
>
>      public static void main(String args[])
>      {
>          java.awt.EventQueue.invokeLater(new Runnable()
>          {
>              public void run()
>              {
>                  new Test_SwingWorker().setVisible(true);
>              }
>          });
>      }
>
> class Non_GUI_Stuff extends SwingWorker<Integer, Integer>
> {
>    protected Integer doInBackground() throws Exception
>    {
>        //"for" loops mentioned above
>        for (int i = 0;i < 100000; i++)
>            for (int i2 = 0;i2 < 100000; i2++);
>        for (int i3 = 0;i3 < 100000; i3++);
>
>      return 0;
>    }
>
>    protected void done()
>    {
>        //The "Hello World" label that disappears
>        jLabel1.setVisible (false);
>    }
> }
>
>      private javax.swing.JButton jButton1;
>      private javax.swing.JLabel jLabel1;
>      private javax.swing.JPanel jPanel1;
> }
>

Read the docs dude "SwingWorker is only designed to be executed once. 
Executing a SwingWorker more than once will not result in invoking the 
doInBackground method twice."

Just create a new SwingWorker Object and execute it again.

Your code is hard to follow and overly verbose.  You could simplify it 
by importing more classes.  I would put the variable declarations at the 
top somewhere, not because they don't work there but because it is where 
one would expect to find it.

Below find some sample code for a very simple task, drawing in response 
to a button press.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class test extends JPanel implements ActionListener {
     private String state = "";

     public test() {
         setPreferredSize(new Dimension(400,300));
     }

     public void actionPerformed(ActionEvent ae) {
         state = ae.getActionCommand();
         repaint();
     }

     public void paintComponent(Graphics g) {
         g.setColor(getBackground());
         g.fillRect(0,0,getWidth(),getHeight());
         g.setColor(getForeground());
         if (state.equals("Line"))
             g.drawLine(0,0,getWidth(),getHeight());
         else if (state.equals("Oval"))
             g.drawOval(0,0,getWidth(),getHeight());
         else if (state.equals("Rect"))
             g.drawRect(5,5,getWidth()-10,getHeight()-10);
     }

     public static void main(String[] args) {
         EventQueue.invokeLater(new Runnable() {
             public void run() {
                 test t = new test();
                 JFrame f = new JFrame("test");
                 f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                 f.add(t,BorderLayout.CENTER);
                 JPanel p = new JPanel();
                 JButton b = new JButton("Line");
                 b.addActionListener(t);
                 p.add(b);
                 b = new JButton("Oval");
                 b.addActionListener(t);
                 p.add(b);
                 b = new JButton("Rect");
                 b.addActionListener(t);
                 p.add(b);
                 f.add(p,BorderLayout.NORTH);
                 f.pack();
                 f.setVisible(true);
             }
         });
     }
}

And a simplified example similar to what you were trying to do.

import java.awt.*;
import java.awt.event.*;
import java.util.concurrent.*;
import javax.swing.*;

public class test2 extends JPanel {
     private final JLabel label;

     private int count = 0;

     public test2() {
         super(new GridBagLayout());

         setPreferredSize(new Dimension(320,240));

         GridBagConstraints c = new GridBagConstraints();
         c.insets = new Insets(2,2,2,2);

         c.gridy = 0;
         c.anchor = GridBagConstraints.NORTH;
         JButton b = new JButton("Hello");
         b.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent ae) {
                 (new DelayWorker()).execute();
             }
         });
         add(b,c);

         ++c.gridy;
         c.anchor = GridBagConstraints.CENTER;
         c.weightx = c.weighty = 1.0;
         label = new JLabel("");
         add(label,c);
     }

     class DelayWorker extends SwingWorker<Integer,Object> {
         public Integer doInBackground() throws InterruptedException {
             ++count;
             Thread.sleep(1000);
             return count;
         }

         public void done() {
             try {
                 label.setText(get().toString());
             } catch (InterruptedException ie) {
                 ie.printStackTrace();
             } catch (ExecutionException ee) {
                 ee.printStackTrace();
             }
         }
     }

     public static void main(String[] args) {
         EventQueue.invokeLater(new Runnable() {
             public void run() {
                 JFrame f = new JFrame("test2");
                 f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                 test2 t2 = new test2();
                 f.add(t2,BorderLayout.CENTER);
                 f.pack();
                 f.setVisible(true);
             }
         });
     }
}



-- 

Knute Johnson

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.java.programmer


csiph-web