0
   public class frame11 extends javax.swing.JFrame implements ActionListener,
    PropertyChangeListener {


 public String[] columnNames = { "Path",
                    "File Name",
                    "Size"};
       public  Object[][] data ;
int isJPEG (String s) throws IOException
   { int c=0;//not jpeg

    if ( (s.endsWith(".JPG")) || (s.endsWith(".JPEG"))||(s.endsWith(".jpeg"))||(s.endsWith(".jpg")))
{

                c=1;//is jpeg

}
   return c;
   }

           }


    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)     {//GEN-FIRST:event_jButton1ActionPerformed

    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    JFileChooser fch = new JFileChooser("C:\\");
   jProgressBar1.setValue(0);
    jProgressBar1.setStringPainted(true);
    jTextField1.setText(null);
    jTextField2.setText(null);
    jTextField4.setText(null);
    jLabel7.setText(null);
    data = new Object[15][3]; 
    jTable2.setModel(new DefaultTableModel(data, columnNames));
    fch.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int ret = fch.showOpenDialog(null);
    int apr=0;
    if (ret==JFileChooser.APPROVE_OPTION)
    {     apr=1;
        jTextField1.setText(fch.getSelectedFile().toString());
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    }
    else jTextField1.setText("Nothing clicked!!!");
    if (apr==1)   {
    jLabel7.setText("Wait Please, While searching ...");
    task = new Task();
    task.addPropertyChangeListener(this);
    task.execute();
    EventQueue.invokeLater(new Runnable() { // Added

            @Override
            public void run() {
                File f = fch.getSelectedFile();
        String s= f.getAbsolutePath();
        int cnt;
        int st=0;
        Path myfile = Paths.get(s);
        if(f.isDirectory()&& Files.isReadable(myfile)){
        try {
        st=st+CheckFiles(f);
        cnt=count(f);
        String ss=Integer.toString(cnt);
        jTextField2.setText(ss);
        jTextField4.setText(Integer.toString(st)); 
        } catch (IOException ex) {
        Logger.getLogger(frame1.class.getName()).log(Level.SEVERE, null, ex);
        }
        }
       jLabel7.setText("Scanning Finished. Thanks for waiting ");
    }

            });

    }

}//GEN-LAST:event_jButton1ActionPerformed
private Task task; 
@Override
public void propertyChange(PropertyChangeEvent evt) {
    if ("progress".equals(evt.getPropertyName())) {
        int progress = (Integer) evt.getNewValue();
        jProgressBar1.setValue(progress);
     System.out.println("Property changed");
    } 
}

//@Override
public void actionPerformed(ActionEvent e) {

}

  class Task extends SwingWorker<Void, Void> {
    @Override
    public Void doInBackground() {
        Random random = new Random();
        int progress = 0;
        setProgress(0);
        while (progress < 100) {
            try {
                Thread.sleep(random.nextInt(100));
            } catch (InterruptedException ignore) {}
            progress += random.nextInt(10);
            setProgress(Math.min(progress, 100));
        }
        return null;
    }

    /*
     * Executed in event dispatching thread
     */
    @Override
    public void done() {
        Toolkit.getDefaultToolkit().beep();
        setCursor(null); 
    }
}

I would like your help, I'm trying to scan my pc for JPEG images to count them. I have two problems, the first is that I'm using a jtable, but the results is never added until the program ends, and the progress bar isn't synchronized sometimes it ends before the program and sometimes after. please help me resolve these two problems and thank you.

sosono
  • 13
  • 1
  • 5

1 Answers1

2

You're using a SwingWorker in order to create a background thread -- good -- but you're making Swing calls directly from that background thread -- bad:

jProgressBar1.setValue(n);

Instead call setProgress(...) from within your SwingWorker, and add a PropertyChangeListener to the worker that listens for changes to the worker's "progress" bound property.

For examples:


For an example of an mcve that shows an example of use of a JProgressBar with a SwingWorker:

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import javax.swing.*;

@SuppressWarnings("serial")
public class TestProgress2 extends JPanel {
   private JProgressBar progressBar = new JProgressBar(0, 100);
   private Action startBackgroundTaskAction = new StartBackgroundTaskAction();

   public TestProgress2() {
      progressBar.setStringPainted(true);
      add(progressBar);
      add(new JButton(startBackgroundTaskAction));
   }

   public void setActionEnabled(boolean enabled) {
      startBackgroundTaskAction.setEnabled(enabled);
   }

   private class StartBackgroundTaskAction extends AbstractAction {
      public StartBackgroundTaskAction() {
         super("Start Background Task");
         putValue(MNEMONIC_KEY, KeyEvent.VK_S);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         progressBar.setString(null);
         progressBar.setValue(0);
         setActionEnabled(false);
         MyTask myTask = new MyTask();
         myTask.addPropertyChangeListener(new MyTaskListener());
         myTask.execute();
      }
   }

   private class MyTaskListener implements PropertyChangeListener {
      @Override
      public void propertyChange(PropertyChangeEvent pcEvt) {
         MyTask myTask = (MyTask) pcEvt.getSource();
         if ("progress".equals(pcEvt.getPropertyName())) {
            int progress = myTask.getProgress();
            progressBar.setValue(progress);
         }
         if (pcEvt.getNewValue() == SwingWorker.StateValue.DONE) {
            setActionEnabled(true);
            progressBar.setString("Done");
            try {
               myTask.get();
            } catch (InterruptedException e) {
               e.printStackTrace();
            } catch (ExecutionException e) {
               e.printStackTrace();
            }
         }
      }
   }

   private class MyTask extends SwingWorker<Void, Void> {
      @Override
      protected Void doInBackground() throws Exception {
         Random random = new Random();
         int progress = 0;
         setProgress(0);
         while (progress < 100) {
             try {
                 Thread.sleep(random.nextInt(1000));
             } catch (InterruptedException ignore) {}
             progress += random.nextInt(10);
             setProgress(Math.min(progress, 100));
         }
         return null;
      }
   }

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

      JFrame frame = new JFrame("TestProgress2");
      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
  • It's my first time using jprogress bar, Can you please give me more details or suggest me a good tutorial. Thank you so much. – sosono Apr 23 '15 at 18:35
  • @sosono: please see links to my code examples in the edit to my answer. Also the JProgressBar tutorial I think has an example. – Hovercraft Full Of Eels Apr 23 '15 at 18:41
  • I Still have the same problem i will update the code please tell me what did i do wrong. thanks. – sosono Apr 23 '15 at 20:49
  • @sosono: Please create and post a small but simple complete program that illustrates your problem, an [MCVE](http://stackoverflow.com/help/mcve). Please check the link for the details of this very useful tool. – Hovercraft Full Of Eels Apr 23 '15 at 22:14
  • please check my previous post, I wrote everything but the function checkfiles that counts the number of jpeg files in a directory – sosono Apr 23 '15 at 22:29
  • @sosono: if you mean the code in your original question, yes, I've checked it, but I cannot copy and paste it into my IDE and compile and run it, so I'm stuck. I don't want to see your whole program as that would overwhelm us with much code not relevant to your problem, but I do want to see relevant code that I can compile and run. Again if you want the best chance of our understanding your problem, consider creating and posting a [minimal compilable, runnable, example program or MCVE](http://stackoverflow.com/help/mcve). – Hovercraft Full Of Eels Apr 23 '15 at 22:31
  • @sosono: for an example of just what I mean, see my [MCVE](http://stackoverflow.com/help/mcve) that I've posted as an edit to my answer that uses some of your code. – Hovercraft Full Of Eels Apr 23 '15 at 22:49
  • @sosono: yikes! try to avoid the NetBeans generated code when creating minimal programs. Also why the JTable? What relevance does that have to your problem? Again, please pare down your code to the bare minimum required. Have you gone through my minimal code example? Edit: and your code won't compile as it's missing a bunch of variables. Again, please pare it down, and please test it before posting it here. Your code is not well formatted (something your IDE should do for you) making it hard to read... – Hovercraft Full Of Eels Apr 23 '15 at 23:37
  • I'm sorry for that, the jtable is very important to me, I need it to be updated with the JPEG file name when found. I don't know what IDE you are using. should I just send you the file instead, you can just copy and paste in your project and run it. – sosono Apr 24 '15 at 08:44
  • @sosono: I've no doubt that the JTable is important to you, but the question remains -- **what relevance does it have for your current problem**? No, don't send the entire file, and the IDE makes no difference at all, since a minimal program should compile and run off of the command line. If you are still having problems, just create and post a [minimal example program](http://stackoverflow.com/help/mcve) as I have done in my answer above. Shoot, use my code above as a framework for your example. Otherwise you'll be sending large code, most of it completely irrelevant to the problem at hand. – Hovercraft Full Of Eels Apr 24 '15 at 11:02
  • Thx a lot for your help. I found the solution to my problem. It's to call the function (taking a long time to execute) from within the task. – sosono Apr 24 '15 at 16:46
  • @sosono: glad you found the solution. If it is being called from within the background task though, it shouldn't be causing the problem. – Hovercraft Full Of Eels Apr 24 '15 at 16:57