0

Please help. This code isn't working. The progress bar is created and 0% is showing in it that's all. I don't know much about java.i'm looking for some help.

Original code:

 jProgressBar1.setName("");
        jProgressBar1.setValue(0);
        jProgressBar1.setStringPainted(true);
        jProgressBar1.addContainerListener(new java.awt.event.ContainerAdapter() {
            public void componentAdded(java.awt.event.ContainerEvent evt) {
                jProgressBar1ComponentAdded(evt);
            }
        });
private void jProgressBar1ComponentAdded(java.awt.event.ContainerEvent evt) {                                             

    Task tk = new Task();
    tk.run();

        }    

 class Task extends Thread {    
    public Task(){}

    public void run(){
       for(int i =0; i<= 100; i++){
          final int progress = i;
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                 jProgressBar1.setValue(progress);

             }
          });
       }}}

Latest code:

import java.awt.event.ContainerAdapter;
import java.awt.event.ContainerEvent;

import javax.swing.*;




public class ini extends JFrame {


    public ini() {
        initComponents();

    }

    private void initComponents() {

            setResizable(false);
            jLabel1 = new JLabel();
            jProgressBar1 = new JProgressBar(0,100);
            jProgressBar1.addContainerListener(new ContainerAdapter() {
                @Override
                public void componentAdded(ContainerEvent e) {
                   if (jProgressBar1 == e.getChild()) {
                      System.out.println("progressBar!");
                      new Thread(new Task()).start();
                   }
                }
             });

            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("Criminal Records");

            jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
            jLabel1.setText("Criminal Records");

            jProgressBar1.setName("");
            jProgressBar1.setValue(0);
            jProgressBar1.setStringPainted(true);

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(204, 204, 204)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 254, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(215, 215, 215)
                            .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addContainerGap(242, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(312, 312, 312)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(348, Short.MAX_VALUE))
            );

            pack();

     }


    public static void main(String args[]) {


        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ini.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ini.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ini.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ini.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }


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

    private class Task implements Runnable {
        private static final long SLEEP_TIME = 100;

        @Override
        public void run() {
           for (int i = 0; i <= 100; i++) {
              final int progress = i;
              SwingUtilities.invokeLater(new Runnable() {
                 public void run() {
                    jProgressBar1.setValue(progress);

                 }
              });
              try {
                 Thread.sleep(SLEEP_TIME);
              } catch (InterruptedException e) {
                 e.printStackTrace();
              }
           }
        }
     }


    private javax.swing.JLabel jLabel1;
    private javax.swing.JProgressBar jProgressBar1;
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Jithin Sebastian
  • 511
  • 1
  • 6
  • 19
  • You need to tell us just what you're trying to achieve with this code. Why are you using a ContainerListener? For what purpose? – Hovercraft Full Of Eels Sep 13 '14 at 11:49
  • 1
    Also your use of threading is incorrect. You should implement a Runnable, not extend Thread, and when you start a thread, call `.start()` on it, not `.run()`, as the latter will guarantee that a background thread will not be made. – Hovercraft Full Of Eels Sep 13 '14 at 11:51

1 Answers1

1

I see one major and one minor problem with your use of threading:

  • Minor problem: You should implement a Runnable, not extend Thread, since this separates the code run by the Thread from the Thread, following the single responsibility rule, and gives the code that the thread is running more flexibility, since now it can extend other classes if need be.
  • When you start a thread, call .start() on it, not .run(), as the latter will guarantee that a background thread will not be made.

As for your other issue, that of the use of a ContainerListener, I await your clarification of your problem, and your creating and posting your minimal code example program for us to review, test, and possibly fix.


Edit
per your comment,

I want to show a progress-bar in a frame which show 0-100%. I created the frame and added the progress bar. But it shows only 0% and not moving.

Again, you have some threading issues that need to be fixed. You'll also want to put a Thread.sleep in there to slow your for loop down. Otherwise, even with proper threading, you will not see progress.

I want to invoke the function when progressbar is added to the frame.

You're adding a ContainerListener to the JProgressBar which won't work, since you aren't adding anything into the progressbar. You would instead need to add the listener to the container that holds the progressbar. But even so, this is probably not a great way to start the process. But let me see what I can do.... hang on please.


e.g.,

import java.awt.event.ContainerAdapter;
import java.awt.event.ContainerEvent;

import javax.swing.*;

public class JProgressExample extends JPanel {
   private JProgressBar jProgressBar1 = new JProgressBar(0, 100);

   public JProgressExample() {
      addContainerListener(new ContainerAdapter() {
         @Override
         public void componentAdded(ContainerEvent e) {
            if (jProgressBar1 == e.getChild()) {
               System.out.println("progressBar!");
               new Thread(new Task()).start();
            }
         }
      });
      jProgressBar1.setName("");
      jProgressBar1.setValue(0);
      jProgressBar1.setStringPainted(true);

      add(jProgressBar1);
   }

   private class Task implements Runnable {
      private static final long SLEEP_TIME = 100;

      @Override
      public void run() {
         for (int i = 0; i <= 100; i++) {
            final int progress = i;
            SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                  jProgressBar1.setValue(progress);

               }
            });
            try {
               Thread.sleep(SLEEP_TIME);
            } catch (InterruptedException e) {
               e.printStackTrace();
            }
         }
      }
   }

   private static void createAndShowGui() {
      JProgressExample mainPanel = new JProgressExample();

      JFrame frame = new JFrame("JProgressExample");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • I want to show a progress-bar in a frame which show 0-100% . I created the frame and added the progress bar. But it shows only 0% and not moving. I want to invoke the function when progressbar is added to the frame. – Jithin Sebastian Sep 13 '14 at 12:30
  • @JithinSebastian: please see edit to answer. See next edit. You're adding a container listener to the wrong container. – Hovercraft Full Of Eels Sep 13 '14 at 12:33
  • Will adding a component listener to progressbar ComponentShown help? – Jithin Sebastian Sep 13 '14 at 12:41
  • @JithinSebastian: For example, please see the code above. I've added the ContainerListener to the main JPanel that is holding the JProgressBar and have added Thread.sleeps to it. – Hovercraft Full Of Eels Sep 13 '14 at 12:41
  • still no progress. just added my whole program to the question. please take a look at it and answer. – Jithin Sebastian Sep 13 '14 at 13:08
  • @JithinSebastian: I have already posted the solution, one you haven't commented on at all. Please take a look at it first and ask if anything confuses you before asking me to do **more** work and likely unnecessary work! Please remember that we are volunteers here and our time is valuable. – Hovercraft Full Of Eels Sep 13 '14 at 13:09
  • @JithinSebastian: and you're ***still*** adding the ContainerListener to the JProgressBar, almost as if you're ignoring all that I've posted. – Hovercraft Full Of Eels Sep 13 '14 at 13:11
  • i used it without jprogressbar but nothing happened. so i added it to see will something happen. i think i have a hard time ahead understanding this language clearly. – Jithin Sebastian Sep 13 '14 at 13:15
  • @JithinSebastian: again, if something in my answer or code is confusing, please ask for clarification. – Hovercraft Full Of Eels Sep 13 '14 at 13:38
  • @JithinSebastian: other suggestions: 1) It's always a good idea to be sure that your understanding of the Java basics are decent before embarking on GUI creation. I continually study the basics myself, as there's always something new to learn. 2) Avoid using a GUI code generator until you have first gained a decent understanding of the underlying GUI library. It's better to code Swing GUI's by hand when starting out. – Hovercraft Full Of Eels Sep 13 '14 at 13:46
  • i figured it out at last. I used an object of class with code you provided. and with some small modifications it worked. – Jithin Sebastian Sep 13 '14 at 17:22
  • @JithinSebastian: I'm glad that you've got it working. Note that I still stand by my recommendation of not starting the thread inside of a ContainerListener. Instead it would be better to start it on program start up or inside of a JButton's ActionListener. I'd favor the latter, of using an ActionListener. – Hovercraft Full Of Eels Sep 13 '14 at 17:24