Results 1 to 17 of 17
  1. #1
    cotarelo is offline Member
    Join Date
    Mar 2010
    Posts
    43
    Rep Power
    0

    Question SwingWorker question

    I am a novice-java programmer and currently I am developing a graphical swing interface (GUI.java) for a console-based algorithm (algorithm.java).

    In my graphical interface, when I click on the "run algorithm" button, the algorithm is executed and the results which previously were written in the console, now they are written in a text area inside the GUI. The problem is that until the computation is not finished (all results are printed) the textarea is not updated, and the GUI gets irresponsible.

    I know I have to do it with a Swing Worker but in all the examples that I found the swing workers run on the same class and therefore is easier

    This is a part of code (algorithm.java) which displays the printed results of the algorithm into the textarea:

    Java Code:
    for (;;) {
    
    			System.step();
    
    				if (step % SCREEN_INTERVAL == 0) {
    				step++;
    
                                    // output = output of program (each LiNE)
                                    output = String.format(
    						"%d\tA=%d\tBt=%d\tRsp=%d\tE=%d\t+=%d\t-=%d\tdr=%d\tF=%d\tFF=%d\t\tB=%d\tLV=%3.2f\n",step - 1, System.gC(), Stats.b, Stats.r, NS.gEC(), Stats.a, Stats.r, Stats.dr, Stats.f, Stats.ff, Stats.b, Stats.l());
    
    			//  output before the gui
                            //        System.out.println(output);
    
                            // Write into a output file (pw = PrintWriter)
    
                             pw.println(output);
    
    
                             // write output into the gui (TEXTAREA)
                             GUI.jtxaConsole.append(output);
    
    
                                       Stats.reset();
    			} else
    				step++;
    		}
    Help is appreciated.
    Thanks!

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    If the code above is in the SwingWorker's doInBackground method, then it suggests that you're trying to update a Swing component directly from the background thread, which is not what you want to be doing. Are you using the SwingWorker's publish/process methods? If not you should as these would allow you to do what you want easily. The Sun tutorial on this can show you the way.

    You also look to be doing things here in a static and not OOPs way. If so, you may wish to correct this. Best of luck!

  3. #3
    cotarelo is offline Member
    Join Date
    Mar 2010
    Posts
    43
    Rep Power
    0

    Default

    Could you illustrate me with an example?

    Thank you in advance

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Heck, a simple example:
    Java Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.List;
    
    import javax.swing.*;
    
    public class FuSwing {
      private static void createAndShowGUI() {
        final FuSwingGui gui = new FuSwingGui();
    
        gui.doItAddActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            gui.start();
            new MySwingWorker(gui).execute();
          }
        });
    
        JFrame frame = new JFrame("FuSwing Application");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(gui.getMainPanel());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
          }
        });
      }
    }
    
    class FuSwingGui {
      private JPanel mainPanel = new JPanel();
      private JTextArea textarea = new JTextArea(15, 20);
      private JButton doItButton = new JButton("Do It!");
    
      public FuSwingGui() {
        textarea.setEditable(false);
        textarea.setFocusable(false);
        
        mainPanel.add(new JScrollPane(textarea, 
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, 
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
        mainPanel.add(doItButton);
      }
    
      public void doItAddActionListener(ActionListener al) {
        doItButton.addActionListener(al);
      }
    
      public void appendToTextArea(String text) {
        textarea.append(text);
      }
    
      public void start() {
        doItButton.setEnabled(false);
      }
    
      public void done() {
        doItButton.setEnabled(true);
      }
    
      public JPanel getMainPanel() {
        return mainPanel;
      }
    
    }
    
    class MySwingWorker extends SwingWorker<Void, String> {
      private FuSwingGui gui;
    
      public MySwingWorker(FuSwingGui gui) {
        this.gui = gui;
      }
    
      @Override
      protected Void doInBackground() throws Exception {
        for (int i = 0; i < 20; i++) {
          String text = "From Swing Worker: " + (i + 1);
          publish(text);
          System.out.println(text);
          Thread.sleep(500);
        }
        return null;
      }
    
      @Override
      protected void process(List<String> chunks) {
        for (String text : chunks) {
          gui.appendToTextArea(text + "\n");
        }
      }
    
      @Override
      protected void done() {
        gui.done();
      }
    
    }

  6. #6
    cotarelo is offline Member
    Join Date
    Mar 2010
    Posts
    43
    Rep Power
    0

    Default

    I have read the tutorials, my problems is that I created the application with the netbeans assistant and there is no such method createandshowgui() in the gui;besides the operation to do in background is a different algorithm in another package and different class. so I dont know where to put the do in background method.

    Anyway in the example you pasted me when i comment the lines:

    Java Code:
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run()
    Application works in the same way, I would be interested in the same piece of code but without the swingworker code, to check where I should put the methods.

    Thanks and sorry but I am really newbie

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I don't understand what you're asking here. Please outline anything specific that you don't understand about my post.

    While I do think that it's fine to use NetBeans as an IDE, at this stage you should not be using NetBeans to generate your GUI code. Rather you should be learning to create it yourself by hand since if you did, I think that you'd understand the code that I posted.

  8. #8
    cotarelo is offline Member
    Join Date
    Mar 2010
    Posts
    43
    Rep Power
    0

    Default

    I understand the code you posted, but realize swingworker in my case is more complicated.

    Please, I would like the same example, but without the swingworker, so I can see how and where you added the different methods and where and how the concurrency works.

    ignore what i said about netbeans.

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by cotarelo View Post
    I understand the code you posted, but realize swingworker in my case is more complicated.

    Please, I would like the same example, but without the swingworker, so I can see how and where you added the different methods and where and how the concurrency works.
    I'm sorry, but I'm still not getting you. To see my code without the SwingWorker, simply get rid of the MySwingWorker class and comment out the use of this class in the action listener:
    Java Code:
        gui.doItAddActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            gui.start();
            // new MySwingWorker(gui).execute();
          }
        });


    I still think that for us to help you better you need to write out a well-formed paragraph about just what's not working for you. Also look into creating and posting an SSCCE or "Short, Self Contained, Correct (Compilable), Example" so we can see a small portion of your code that well illustrates your current problem.

  10. #10
    cotarelo is offline Member
    Join Date
    Mar 2010
    Posts
    43
    Rep Power
    0

    Default

    Another try:

    I have graphical swing interface (GUI.java) for a console-based algorithm (algorithm.java). Inside the constructor of algorithm.java there is a method execute() which do some computations and prints them into a text area.

    In my graphical interface, when I click on the "run algorithm" button, the algorithm.java is executed. The problem is that until the computation is finished the GUI gets irresponsible.

    I implemented the Swingworker in my algorithm.java:

    Java Code:
    public class Algorithm extends SwingWorker {
    
    public Algorithm{
    ...
    
    this.doInBackground();
    }
    
    public void execute(){
    
    /* here they go computations */
    ...
    
    @Override
    protected Object doInBackground() throws Exception {
    this.execute();
    }
    
    }
    It does not solve my problem.

    in my GUI.java in the actionperformed of the "Run Algorithm" Button

    Java Code:
    public class GUI extends FrameView {
    ...
    
    private void goButtonActionPerformed(java.awt.event.ActionEvent evt) {
    Algorithm algo = new Algorithm(arrayArgum, outputpath, this);
    algo.execute();
    }
    
    }
    Help?
    Last edited by cotarelo; 03-19-2010 at 04:30 PM.

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    What's this about?
    Java Code:
    public Algorithm{
    ...
    
    this.doInBackground();  // *** holy mackerel!?! ***
    
    }

    This will mess you up royally and cause all of the background stuff to be called on the EDT. So don't do this. In fact, there's a good chance that this may be the source of your problems.

    If you still are having problems, then again, create an SSCCE and post it. The link is in my post above.
    Last edited by Fubarable; 03-19-2010 at 08:46 PM.

  12. #12
    cotarelo is offline Member
    Join Date
    Mar 2010
    Posts
    43
    Rep Power
    0

    Exclamation

    Thanks for the reply, my code was very messy and I have some mistakes. Now I am getting closer, as the multi threading seems to work, but, still I can not do what I want.

    This is my code in GUI.java

    Java Code:
    ...
    
    private void goButtonActionPerformed(java.awt.event.ActionEvent evt) {  
    
            goButton.setEnabled(false);  // An additional line.
             computeTask = new ComputeTask(this);
             computeTask.execute();
    }         
    ...
    private class ComputeTask extends SwingWorker{
    
    ...
            GUI view;
    ...
    
            private ComputeTask(GUI v) {
                view = v;
            }
    
    ..
    
    @Override
            protected Void doInBackground() throws IOException {
    
      Algorithm algo = new Algorithm(arrayArgum, outputpath, view);
    
                for (int i = 0; i < 2000000; i++) {
                String text = "From Swing Worker: " + (i + 1)+"\n";
                textarea.append(text);
                }
                goButton.setEnabled(true);
    
            return null;
            }
                }
    For some reason, in the Doinbackground method, I receive the "From Swing worker" text on the textarea, but the call to the algorithm is never done, and I do not receive the results of the computations in the textarea. Of course without the swingworker the call to the algorithm works.

  13. #13
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by cotarelo View Post
    Thanks for the reply, my code was very messy and I have some mistakes. Now I am getting closer, as the multi threading seems to work, but, still I can not do what I want.

    This is my code in GUI.java
    For some reason, in the Doinbackground method, I receive the "From Swing worker" text on the textarea, but the call to the algorithm is never done, and I do not receive the results of the computations in the textarea. Of course without the swingworker the call to the algorithm works.
    I have requested several times for an SSCCE. If you are serious about needing help, then it would be in your best interest to make the effort to read the link about this, create one, and post it. Otherwise I only have partial information, and certainly not enough to be able offer advice. Up to you.

    Best of luck.

  14. #14
    cotarelo is offline Member
    Join Date
    Mar 2010
    Posts
    43
    Rep Power
    0

    Default

    My only problem is that this call inside the Doinbackgound method.

    Java Code:
      Algorithm algo = new Algorithm(arrayArgum, outputpath, view);
    Seems to never be done. The algorithm should answer in my textarea with results (if I place the call outside the the swingworker method it does it correctly).

    However, the text From Swing Worker: 1
    From Swing Worker: 2.
    ...

    It does it correcly, and I can move the scroll bar in the textarea when it is still running

  15. #15
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by cotarelo View Post
    My only problem is that this call inside the Doinbackgound method.

    Java Code:
      Algorithm algo = new Algorithm(arrayArgum, outputpath, view);
    Seems to never be done. The algorithm should answer in my textarea with results (if I place the call outside the the swingworker method it does it correctly).

    However, the text From Swing Worker: 1
    From Swing Worker: 2.
    ...

    It does it correcly, and I can move the scroll bar in the textarea when it is still running
    Isolate the problem by creating an SSCCE. Seriously, it works.

  16. #16
    cotarelo is offline Member
    Join Date
    Mar 2010
    Posts
    43
    Rep Power
    0

    Default

    The view was redeclared
    Java Code:
     GUI view;
    And that is why it was not passing the parameters.
    PS: I tried to do a SSCCE but I did not know how, the page is very unclear, and sure an poster does not want to loose time on this. maybe a tutorial in this forum would work

  17. #17
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by cotarelo View Post
    The view was redeclared
    Java Code:
     GUI view;
    And that is why it was not passing the parameters.
    and can you see why there's no way we can see that this was your problem given what you've posted above? An SSCCE would have shown this to us days ago.

    PS: I tried to do a SSCCE but I did not know how, the page is very unclear, and sure an poster does not want to loose time on this. maybe a tutorial in this forum would work
    It's a pretty straight forward process of trying to isolate your problem into a small compilable program that we can run and view. Why don't you let us know what parts about the page are confusing and we can help you with it. Otherwise we will all continue to be frustrated by your posting snippets of code that don't contain the actual problem, and that we can't run or test. Thus if you had posted a proper SSCCE in the first place, you'd likely have had your solution days ago and would have saved time,... but it's your dollar.

Similar Threads

  1. SwingWorker Problem
    By Berkan in forum Threads and Synchronization
    Replies: 10
    Last Post: 03-11-2010, 04:28 AM
  2. Replies: 18
    Last Post: 10-13-2009, 04:00 PM
  3. SwingWorker Opinions
    By frejon26 in forum AWT / Swing
    Replies: 3
    Last Post: 04-13-2009, 09:41 PM
  4. Replies: 3
    Last Post: 10-02-2008, 06:48 AM
  5. swingworker
    By musiigedeo in forum AWT / Swing
    Replies: 1
    Last Post: 07-26-2007, 01:59 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •