2

I have a main class(which is basically a netbeans form;drag and drop) from where my application starts and another class(call it class 2) where my functions resides.I first call a function in class2 from my main method and that method has a while loop which increments a counter.Depending on that counter i call a function of my main class and try to display the counter in a textfield and also st the progressbar in intermediate but it is not working though it shows the print statements correctly(the counter).

Some code i am adding it is giving me problem as it is neither updating the progressbar nor updating the textfield.Kindly help me why is this happening

i have edited the code but still it displays nothing :(

public class NewClass 
{
    public static int counter = 0;
    public  NewJFrame p = new NewJFrame();
    public void packet() 
    {
        try 
        { 
            while (true) 
            {
                //some code ,right now which i have omitted
                counter = counter + 1;
                counter2(counter);
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public void counter2(int counter) 
    {
        counter3();
    }

    public void counter3() 
    {

        p.progress(counter);
    }
}

Now here is the main method from where i call the functions present in other class()code of that is given above)

public class NewJFrame extends javax.swing.JFrame 
{

    /** Creates new form NewJFrame */
    public NewJFrame() 
    {
        initComponents();
    }

    @SuppressWarnings("unchecked")   
    public void progress(int y)
    {
        jProgressBar1.setIndeterminate(true);
        jTextField1.setText(y+"packets processed");
        System.out.println(y);
    }

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) 
    {    
        NewClass m=new NewClass();
        m.packet();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) 
    {         
        try 
        {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }

        java.awt.EventQueue.invokeLater(new Runnable() 
        {
            public void run() 
            {
                new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
}
Xara
  • 8,748
  • 16
  • 52
  • 82
  • 2
    You are creating a New Object of your `NewJFrame` class inside `counter3()` method, with each iteration of the `while` loop. Create Only a single instance, and use that instance to update values :-) – nIcE cOw Apr 01 '12 at 09:13
  • @GagandeepBali Oh yes u r right but still it displays nothing :( – Xara Apr 01 '12 at 09:22
  • 2
    @Zara : Your while loop in that example is blocking the EDT, try to add something like `if (counter == 10) break;` then it will print, if you adhere to what i suggested in the previous comment :-) . Seems like that while loop is exactly the situation when one should be using a [SwingWorker](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html) – nIcE cOw Apr 01 '12 at 09:38
  • 1
    Here [JProgressBar Tutorials](http://docs.oracle.com/javase/tutorial/uiswing/components/progress.html), a very good example, relating to your case is present. Have a look at it :-) – nIcE cOw Apr 01 '12 at 09:44
  • @GagandeepBali so there is no other way to correct this code without using swingworker? btw where to put this counter condition because value of counter according to my code will always be changing... – Xara Apr 01 '12 at 09:45
  • Watch this code I had pasted as an Answer, will delete it , in some time, modified your code to print values :-) – nIcE cOw Apr 01 '12 at 09:47
  • possible duplicate of [Progress bar to run simultaneously with a function(in another class)](http://stackoverflow.com/questions/9962426/progress-bar-to-run-simultaneously-with-a-functionin-another-class) – Robin Apr 01 '12 at 09:50
  • 3
    Why do you start a new question, when your [previous question with the same code](http://stackoverflow.com/questions/9962426/progress-bar-to-run-simultaneously-with-a-functionin-another-class) is not even 3 hours old. If you have new information, just edit your previous question. – Robin Apr 01 '12 at 09:51
  • @Robin i have edited the previous question,this question was little bit different from the previous one... – Xara Apr 01 '12 at 09:54

2 Answers2

4

Here a small example with SwingWorker will help you update your JTextField on the run :

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

public class NewJFrame extends javax.swing.JFrame 
{

    /** Creates new form NewJFrame */
    public NewJFrame() 
    {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationByPlatform(true);

        JPanel contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout());

        jTextField1 = new JTextField(10);
        contentPane.add(jTextField1, BorderLayout.PAGE_START);

        jProgressBar1 = new JProgressBar(0, 100);       
        contentPane.add(jProgressBar1, BorderLayout.CENTER);

        jButton1 = new JButton("START");
        jButton1.addMouseListener(new MouseAdapter()
        {
            public void mouseClicked(MouseEvent me)
            {
                jProgressBar1.setIndeterminate(true);
                jButton1MouseClicked(me);
            }
        });
        contentPane.add(jButton1, BorderLayout.PAGE_END);

        setContentPane(contentPane);
        pack();
        setVisible(true);
    }

    @SuppressWarnings("unchecked")   
    public void progress(final int y)
    {
        System.out.println("progress Method is working.");
        /*
         * This thing needs to be done on Event
         * Dispatcher Thread.
         */
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                jTextField1.setText(y+"packets processed");
                System.out.println(y);
            }           
        });         
    }

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) 
    {    
        NewClass m=new NewClass(this);
        m.execute();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) 
    {         
        try 
        {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }

        java.awt.EventQueue.invokeLater(new Runnable() 
        {
            public void run() 
            {
                new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    public javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
}

class NewClass extends SwingWorker<Void, Void>
{
    public static int counter = 0;
    // Added this variable to keep the instance.
    private NewJFrame p;
    private boolean flag = true;

    public NewClass(NewJFrame frame)
    {
        p = frame;
    }

    public Void doInBackground()
    {
        while(flag)
        {
            counter = counter + 1;
            counter2(counter);
        }
        return null;
    }

    public void done()
    {
        System.out.println("I am DONE");
    }

    public void counter2(int counter) 
    {
        counter3();
    }

    public void counter3() 
    {
        p.progress(counter);
    }
}
nIcE cOw
  • 24,468
  • 7
  • 50
  • 143
  • the statements inside if(counter==10) are causing error that jProgressbar has private access .i have comment off those statements .Now what happens that it displays the result only for packet 10 that packet 10 is processed.I tried to put condition like if(counter>=0) but that doesn't work.... – Xara Apr 01 '12 at 11:05
  • No no, you simply have to use a SwingWorker, if the so called thingy that you are doing inside your `while` loop is a huge task, this example is just to show you that your `while` loop is blocking your EDT, just to update your `JProgressBar` you need to perform this task inside the `while` loop at the background inside `SwingWorker Thread`, so that your `Swing` Application can interact with the user and never will freeze. When you remove that condition, your while loop goes on, which blocks your EDT and your application freezes. – nIcE cOw Apr 01 '12 at 11:26
  • @Zara : Do watch this latest edit of mine, I had used SwingWorker, and it lets you update your `JTextField` on the run :-) – nIcE cOw Apr 01 '12 at 14:00
  • Thanks a lotttt, its working with my code ! btw before i saw ur this post i was learning how to use swingworker :) – Xara Apr 01 '12 at 14:17
  • You are MOST Welcome, but do read SwingWorker, since I am reading that too, might be I had missed something, that you can catch and apply :-) . I am a noob, in SwingWorker :-) – nIcE cOw Apr 01 '12 at 14:20
3

You have got issue with Concurency in Swing

code lines

jProgressBar1.setIndeterminate(true);
jTextField1.setText(y+"packets processed");

should be

java.awt.EventQueue.invokeLater(new Runnable() {

    @Override
    public void run() {
        jProgressBar1.setIndeterminate(true);
        jTextField1.setText(y + "packets processed");
    }
});
mKorbel
  • 109,525
  • 20
  • 134
  • 319