JProgressBar in a JDialog ?

I wished to display my progress bar in a JDialog.
I tried adding the progress bar to an independent JDialog and displayed it and
it seemed to work.
But I wanted a modal JDialog to be part of the JFrame of my application while
showing the progress. This time neither the progress bar that was added is showing up
nor it is getting updated !!
How is this typically implemented ?
It will be great to see a reply from the Swing gurus around so that I complete my application
in a style!
Thanks in advance.

Hi,
I have the same problem. I am trying to add a JProgressBar to a JDialog. I add the timer for the progressbar before the dialog is made visible. But my progressbar fails to display.
A part of my code to illustrate my procedure --
public class ClusterProgressDialog extends JDialog {
    JProgressBar progressBar;
    JLabel currentProcessLabel;
    Timer timer;
    final ClusterProcess clusterProcess;
    public ClusterProgressDialog(Frame parent, String title,
            ClusterProcess process) {
        super(parent, title, false);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        clusterProcess = process;
        currentProcessLabel = new JLabel();
        currentProcessLabel.setBackground(Color.WHITE);
        initialize(parent);
        setVisible(true);
    public void initialize(Frame parent) {
        setSize(300, 100);
        if (!Platform.isMac())
            setBackground(Color.WHITE);
        progressBar = new JProgressBar();
        progressBar.setIndeterminate(true);
        timer = new Timer(100, new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                progressBar.setValue((progressBar.getMaximum() - clusterProcess
                        .getClusterCount()));
                if (clusterProcess.isDone()) {
                    Toolkit.getDefaultToolkit().beep();
                    timer.stop();
                    setVisible(false);
                    dispose();
        JPanel contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout());
        contentPane.add(currentProcessLabel, BorderLayout.NORTH);
        contentPane.add(progressBar, BorderLayout.CENTER);
        Border border = BorderFactory.createMatteBorder(10, 10, 10, 10,
                Color.WHITE);
        contentPane.setBorder(border);
        setContentPane(contentPane);
    public void setLimits(int min, int max) {
        progressBar.setIndeterminate(false);
        progressBar.setMinimum(min);
        progressBar.setMaximum(max);
        progressBar.setValue(min);
        progressBar.setStringPainted(true);
    public void startTimer() {
        timer.start();
}I reuse the progress bar, alternating it between indeterminate and determinate states for different functions in my process being monitored.
Can anyone help me in this?

Similar Messages

  • JProgressBar - monitoring progress of a method in another Object.

    Hi all,
    I've been three days trying to make a JProgressBar work. I know how to use them but not in this case. I'll try to explain the code instead of making you read it.
    -I have a JProgressBar in a JDialog.
    -In the constructor of this class I create a new instance of a Object, call it Processor for example, and i run a method start() on it.
    -This method execute a number of SQL statment and i want to monitor them in the JProgressBar.
    I've followed the official tutorial but it doesnt work for me, I have no idea how to do it beacause i don't know how to refresh the Task process property from outside the doInBackgroundMethod. I also tried to create 2 SwingWorker, run the Processor.run() in one of them, an in run() update a "satic int progress" in each iteration, then from the other SwingWorker i check the Procesor.progress to invoke the setProgress() method.
    I have realised that when debugging sometime it works, so i supposed is something about concurrency, I don't know, please help.
    Thank you in advanced.

    the processor is a runnable, right? then:
    MyDialog extends JDialog{
    private final JProgressBar progressBar= new JProgressBar()
    MyDialog(){...}
    private void init(){
    new SwingWorker<Void,Object>(){
    public Void doInBackground(){
    String sql1=...
    Object o = execute sql1
    publish(o);
    ... do the same with other sql queries
    return null;
    public void process(List<Object> chunks){
    //update progressbar
    //this method will be called using coalescence, so maybe you execute 3 queries, and this method gets called just once, and in this case 'chunks.size()==3'
    public void done(){
    //make sure that the progress is complete, the last chunks may have not been processed through process() method
    progressBar.setValue(100%) // I dont remember the syntax for this
    Edited by: thrawnkb on Jun 3, 2009 3:36 PM

  • Question about the EDT

    Hi everybody,
    Here my issue: I have to write a little something about EDT and the use of SwingUtilities to avoid common issues with the use of Swing. Sure of my knowledge I wrote a little exemple using a progressBar to show how it doesn't work when you don't use SwingUtilities :
    import javax.swing.JDialog;
    import javax.swing.JProgressBar;
    public class UITesting{
        public static void          main                                            ( String[] args ) {
            JProgressBar    jProgressBar    =   new JProgressBar(0, 100) ;
            jProgressBar.setValue(0);
            jProgressBar.setStringPainted(true);
            JDialog         dialog          =   new JDialog() ;
            dialog.setSize(400, 70) ;
            dialog.setContentPane(jProgressBar) ;
            dialog.setLocationRelativeTo(null) ;
            dialog.setVisible(true);
            int flag = 0 ;
            for (int i = 0 ; i < 100000 ; i++) {
                System.out.println(i);
                if ( i%1000 == 0 ) {
                    jProgressBar.setValue(++flag);
                    System.out.println("Increase ProgressBar " + flag);
    }And surprise (at least for me)... it's working... means that my ProgressBar increase well...
    So I write an exemple closer to reality
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    public class UITesting{
        public static void          main                                            ( String[] args ){
            final JProgressBar    jProgressBar    =   new JProgressBar(0, 100) ;
            jProgressBar.setValue(0);
            jProgressBar.setStringPainted(true);
            JButton         start           =   new JButton("Start") ;
            start.addActionListener( new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    int flag = 0 ;
                    for (int i = 0 ; i < 100000 ; i++) {
                        System.out.println(i);
                        if ( i%1000 == 0 ) {
                            jProgressBar.setValue(++flag);
                            System.out.println("Increase ProgressBar " + flag);
            JPanel          panel           =   new JPanel() ;
            panel.add(start) ;
            panel.add(jProgressBar) ;
            JDialog         dialog          =   new JDialog() ;
            dialog.setSize(400, 70) ;
            dialog.setContentPane(panel) ;
            dialog.setLocationRelativeTo(null) ;
            dialog.setVisible(true);
    }That time it's perfect, the ProgressBar doesn't work, it going from 0 to 100% at the end of my for loop and the button freeze during the process, I can illustrate my point and introduce the use of SwingUtilities... But why it's working in my first exemple?
    I know that a call to an ActionListener in a Swing composant insure that the code specified is executed in EDT, but I still can't get it? Someone can help me to understand that ?
    thx in advance,
    yannig
    Edited by: yannig on 24 mars 2011 10:57

    Hi,
    [url http://download.oracle.com/javase/tutorial/uiswing/concurrency/worker.html]Worker Threads and SwingWorker
    When a Swing program needs to execute a long-running task, it usually uses one of the worker threads, also known as the background threads. Each task running on a worker thread is represented by an instance of javax.swing.SwingWorker.
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.*;
    import javax.swing.*;
    public class UITesting2 {
      private SwingWorker<Void, Void> worker;
      public JComponent makeUI() {
        final JProgressBar jProgressBar = new JProgressBar(0, 100);
        jProgressBar.setValue(0);
        jProgressBar.setStringPainted(true);
        final JButton start = new JButton("Start") ;
        start.addActionListener( new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            start.setEnabled(false);
            worker = new SwingWorker<Void, Void>() {
              @Override
              public Void doInBackground() throws InterruptedException {
                int current = 0;
                int lengthOfTask = 1024;
                while (current<=lengthOfTask && !isCancelled()) {
                  Thread.sleep(5);
                  setProgress(100 * current / lengthOfTask);
                  current++;
                return null;
              @Override public void done() {
                start.setEnabled(true);
            worker.addPropertyChangeListener(
                new ProgressListener(jProgressBar));
            worker.execute();
        JPanel panel = new JPanel();
        panel.add(start);
        panel.add(jProgressBar);
        return panel;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          @Override public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new UITesting2().makeUI());
        f.setSize(400, 70);
        f.setVisible(true);
    class ProgressListener implements PropertyChangeListener {
      private final JProgressBar progressBar;
      ProgressListener(JProgressBar progressBar) {
        this.progressBar = progressBar;
        this.progressBar.setValue(0);
      @Override public void propertyChange(PropertyChangeEvent evt) {
        String strPropertyName = evt.getPropertyName();
        if ("progress".equals(strPropertyName)) {
          progressBar.setIndeterminate(false);
          int progress = (Integer)evt.getNewValue();
          progressBar.setValue(progress);
    }

  • Swing Dialog not Showing Content

    Hello,
    I am currently developing code for a complex GUI system and I am experiencing a big problem
    when I try to popup JDialogs. I have a JProgressBar inside a JDialog that pops up when our
    system is doing work. The JDialog pops up but I cannot see the JProgressBar inside the dialog.
    (I also tried to just add a JLabel to the dialog but that doesnt show up either.) When I run my progress
    dialog "stand-alone" I can see the progress bar fine.
    The code for my progress dialog even creates its own thread when it runs so I am pretty sure that
    its not blocking inside my own code.
    This leads me to believe that somewhere in our GUI code we have somehow "blocked" some critical
    AWT (or Swing?) thread and it cannot update the contents of the JDialog.
    Does anyone have an idea as to what could be going on here or how I might find out? I have tried using
    JProbe and Optimizeit Thread profiling tools but they have not really been much help.
    Thanks!
    M.
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dialog;
    import java.awt.Dimension;
    import java.awt.Frame;
    import java.awt.Point;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JProgressBar;
    import javax.swing.SwingConstants;
    public class ProgressAnimationDialog implements Runnable {
         private static final Dimension DIALOGSIZE = new Dimension(200,100);
         private JDialog theDialog;
         private JProgressBar progressBar = new JProgressBar();
         private String string = null;
         private Component owner = null;
         private boolean plainDialog = false;
         public ProgressAnimationDialog(Frame owner, String title) {
              theDialog = new JDialog(owner,true);
              theDialog.setTitle(title);
              this.owner = owner;
              init();
         public ProgressAnimationDialog(Dialog owner, String title) {
              theDialog = new JDialog(owner,true);
              theDialog.setTitle(title);
              this.owner = owner;
              init();
         public ProgressAnimationDialog(Frame owner, String title, String message) {
              theDialog = new JDialog(owner,true);
              theDialog.setTitle(title);
              string = message;
              this.owner = owner;
              init();
         public ProgressAnimationDialog(Dialog owner, String title, String message) {
              theDialog = new JDialog(owner,true);
              theDialog.setTitle(title);
              string = message;
              this.owner = owner;
              init();
         public ProgressAnimationDialog(Frame owner, String title, String message, boolean usePlainDialog) {
              theDialog = new JDialog(owner,true);
              theDialog.setTitle(title);
              string = message;
              this.owner = owner;
              plainDialog = usePlainDialog;
              init();
         public ProgressAnimationDialog(Dialog owner, String title, String message, boolean usePlainDialog) {
              theDialog = new JDialog(owner,true);
              theDialog.setTitle(title);
              string = message;
              this.owner = owner;
              plainDialog = usePlainDialog;
              init();
         private void init() {
              theDialog.setSize(DIALOGSIZE);
              theDialog.setResizable(false);          
              theDialog.getContentPane().setLayout(new BorderLayout());
              if (!plainDialog) {
                   theDialog.getContentPane().add(progressBar,BorderLayout.CENTER);
                   progressBar.setIndeterminate(true);
                   if (string != null) {
                        progressBar.setStringPainted(true);
                        progressBar.setString(string);
              } else {
                   JLabel label = new JLabel("loading region....",SwingConstants.CENTER);               
                   theDialog.getContentPane().add(label,BorderLayout.CENTER);
         public void start() {
              Thread t = new Thread(this);
              t.start();
         public void run() {
              Point p0 = owner.getLocation();
              Point p1 = new Point();
              p1.setLocation(p0.getX()+owner.getWidth()/2.0,p0.getY()+owner.getHeight()/2.0);
              Point p2 = GUIUtilities.getMidPoint(p1,theDialog);
              theDialog.setLocation(p2);          
              theDialog.show();
         public void stop() {
              theDialog.dispose();
         public static void main(String[] args) {
              JFrame frame = new JFrame("Test ProgressAnimationDialog");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(600,400);
              frame.setVisible(true);
              ProgressAnimationDialog pad =
                   new ProgressAnimationDialog(frame,"Please Wait","Loading Region",true);
              pad.start();
              try {
                   Thread.sleep(5000);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              pad.stop();
    }

    Hi Michelle!
    I tried out your code: besides the GUIUtilities class, whose reference I commented out, the program ran perfectly. I got a JProgressBar, with the text in the middle, and the indeterminate bar floating across...
    What version of Java are you using?
    regards,
    lutha

  • JProgressBar inside JDialogBox doesn't show up.

    Hi,
    I have a problem and kind of stuck.
    Here is the scenario.....
    Inside my actionPerformed method I create an instance of a class that extends java.lang.Thread and inside this class run method I create an instance of another class that extends JDialog that contains a JProgressBar. Now when a user clicks a button on the main application window the actionPerformed gets executed and it shows a JProgressBar and then continues the execution of the actionPerformed method while the JProgressBar keeps on updating the status. But the problem is that the JDialog shows up but the JProgressBar inside it doesn't even show. here is the code snippet I am using
    public void actionPerformed(ActionEvent e)
    //some code here
    //class extends Thread and creates JDialog with JProgressBar in it
    //JDialogBox with JProgressBar in it shows here
    t = new ProgressThread();
    t.start();
    //some other code I do some other processing
    //here I am hidding and destroying the JProgressBar
    //inside the reset method I hide the JDialog and set it to null
    t.reset();
    //some more code
    } //end of actionPerform
    Now my problem is that JDialogBox does pop-up but the JProgressBar in it doesn't show. Any ideas what I am doing wrong. I even tried to create the instance of JDialog directly instead of using a separate Thread but it didn't work either.
    Thanks for any help

    The point being, AWT and Swing are, in general, not thread-safe.
    You must not do anything that modifies the appearance of any visible Swing component, such as JProgressBar, from your thread. This must be done in the AWT Event Dispatch Thread. But when the components are not visible, like when you are building your GUI and haven't set it to visible yet, this doesn't apply.
    What I do, when my threads need to update the GUI, is to create a Runnable to do it, then queue that to the AWT Event Dispatch Thread for execution by calling SwingUtilities.invokeLater(). Other people use this SwingWorker class.
    Note that event listener methods are called in the AWT Event Dispatch Thread, so you need to worry about this only in your own thread.
    It is said there are some Swing components that are thread-safe. Given the typical use of JProgressBar, too bad it isn't one of them.

  • Prob with JProgressBar and JButton

    Hi, hopefully someone can help me. I have an applet that does some stuff and when it starts the work, it creates a new JFrame with 2 progress bars (JProgressBar), an ok Jbutton and a cancel JButton. The progress bars update properly, thats not an issue, my problem is that when you click either of the buttons, they don't create an actionEvent until the work is completed, which is ok for the OK button but makes the cancel button pretty useless. I have tried suggested work arounds using SwingWorker and the event dispatching thread for similar probs other people have posted on here but with no success. I don't really know a lot about threads which doesn't really help!! Is it likely to be a thread problem or something to do with event queue which has also been suggested to me. Any help would be greatly appreciated.

    public class ProgressDialog extends JDialog implements Runnable
    private JProgressBar progressBar, totalBar;
    private JButton ok, cancel;
    public ProgressDialog()
    setTitle(dialogTitle);
    setBounds(350,300,300,120);
    //setSize(300,100);
    Container contentPane = getContentPane();
    FlowLayout flow = new FlowLayout();
    contentPane.setLayout(flow);
    JLabel label1 = new JLabel(" Upload progress: ");
    contentPane.add(label1);
    progressBar = new JProgressBar(0,100);
    progressBar.setValue(0);
    progressBar.setStringPainted(true);
    contentPane.add(progressBar);
    JLabel label2 = new JLabel(" Total progress: ");
    contentPane.add(label2);
    totalBar = new JProgressBar();
    totalBar.setValue(0);
    totalBar.setStringPainted(true);
    contentPane.add(totalBar);
    ok = new JButton("OK");
    ok.addActionListener(new ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    contentPane.add(ok);
    cancel = new JButton("Cancel");
    cancel.addActionListener(new ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton2ActionPerformed(evt);
    contentPane.add(cancel);
    setVisible(true);
    setResizable(false);
    Thats near enough the whole class now. Thanks

  • JProgressBar and file transfer

    Hi, I am trying to use a JProgressBar to determine how many bytes have been sent so far. I have constructed the JProgressBar with the maximum size of the file size. For each 'segment' of the file sent, the progress bar should increment using the setProgress() within the SwingWorker class. If I print the values out, they appear to be correct. However, if I use setProgress() the file transfer seems to fail (not even begin).
    Here's the relevant code:
    public class FileTracker extends JDialog implements PropertyChangeListener {
         private JPanel mainPnl = new JPanel(new BorderLayout());
         private JPanel progressBarPnl = new JPanel(new BorderLayout());
         private JPanel midPnl = new JPanel(new GridBagLayout());
         private JPanel bottomPnl = new JPanel(new GridBagLayout());
         private JLabel fileNameLbl = new JLabel("File name: ");
         private JLabel fileNamexLbl = new JLabel();
         private JLabel sizeLbl = new JLabel("File size: ");
         private JLabel sizexLbl = new JLabel();
         private JButton cancelBtn = new JButton("Cancel");
         private JProgressBar progressBar;
         private FileSender fileSender;
         private FileReceiver fileReceiver;
         private File file;
         public FileTracker(JFrame parent, String ip, int port, File file) {
              super (parent);
              this.file = file;
              fileSender = new FileSender(ip, port, file);
              fileSender.addPropertyChangeListener(this);
              fileSender.execute();
              setLocationRelativeTo(null);
              progressBar = new JProgressBar();
              progressBar.setMaximum((int)file.length());
              add(progressBarPanel());
              setResizable(false);
              setTitle("File sending..");
              pack();
              setVisible(true);
         private JPanel progressBarPanel() {
              progressBar.setValue(0);
              progressBar.setEnabled(true);
              progressBar.setStringPainted(true);
              progressBar.setIndeterminate(true);
              progressBarPnl.add(progressBar, BorderLayout.CENTER);
              return progressBarPnl;
         public void propertyChange(PropertyChangeEvent evt) {
            if ("progress" == evt.getPropertyName()) {
                int progress = (Integer) evt.getNewValue();
                if (progressBar.isIndeterminate())
                     progressBar.setIndeterminate(false);
                progressBar.setValue(progress);
                if (fileSender != null && fileSender.isDone())
                     progressBar.setString("Transfer finished");
                if (fileReceiver != null && fileReceiver.isDone())
                     progressBar.setString("Transfer finished");
    }The SwingWorker:
    public class FileSender extends SwingWorker<Void, Void> {
         private Socket socket;
         private FileInputStream fileIn;
         private OutputStream output;
         private File file;
         private byte buffer[];
         private int bufferSize;
         int bytesRead;
         int progress = 0;
         public FileSender(String ipAddress, int port, File file) {
              try {
                   System.out.printf("NOTICE: FileSender initialised. Sending to:%s on port: %d\n", ipAddress, port);
                   socket = new Socket(InetAddress.getByName(ipAddress), port);
                   output = socket.getOutputStream();
                   bufferSize = socket.getSendBufferSize();
                   buffer = new byte[bufferSize];
                   this.file = file;
                   setProgress(0);
              } catch (UnknownHostException e) {
                   // THE USER MUST BE INFORMED THAT THE RECIPIENT COULD NOT BE RESOLVED
                   e.printStackTrace();
              } catch (java.net.ConnectException ce) {
                   // INFORM THE USER THAT THE RECIPIENT COULD NOT BE REACHED
                   ce.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
         public Void doInBackground() {
                   sendFile();
              return null;
         public void sendFile() {
              System.out.printf("NOTICE: Sending file %s   %d bytes formed of %d segments.\n", file.getName(), file.length(), file.length()/bufferSize < 1 ? 1 : file.length()/bufferSize);
              try {
                   fileIn = new FileInputStream(file);
                   while ((bytesRead = fileIn.read(buffer)) > 0) {
                        output.write(buffer, 0 , bytesRead);
                        progress = progress + bufferSize;
                        if (progress  < file.length())
                             setProgress(progress);
                        else
                             setProgress((int)file.length());
                   output.close();
                   fileIn.close();
                   socket.close();
              } catch (FileNotFoundException e) {
                   e.printStackTrace();
              } catch (IOException ioe) {
                   ioe.printStackTrace();
    }This has been bugging me for a long time. Any help/suggestions much appreciated.

    when you create an SSCCE and get rid of all the File, socket, streams and whatnot (something that you should do next time), you notice something funny:
    import java.awt.BorderLayout;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    import javax.swing.SwingWorker;
    public class FileTracker extends JDialog implements PropertyChangeListener
        private static final int MAX = 500;
        private JPanel progressBarPnl = new JPanel(new BorderLayout());
        private JProgressBar progressBar;
        private FileSender fileSender;
        private FileReceiver fileReceiver;
        public FileTracker(JFrame parent)
            super(parent);
            fileSender = new FileSender(MAX);
            fileSender.addPropertyChangeListener(this);
            fileSender.execute();
            setLocationRelativeTo(null);
            progressBar = new JProgressBar();
            progressBar.setMaximum(MAX);
            add(progressBarPanel());
            setResizable(false);
            setTitle("File sending..");
            pack();
            //setVisible(true);
        private JPanel progressBarPanel()
            progressBar.setValue(0);
            progressBar.setEnabled(true);
            progressBar.setStringPainted(true);
            progressBar.setIndeterminate(true);
            progressBarPnl.add(progressBar, BorderLayout.CENTER);
            return progressBarPnl;
        public void propertyChange(PropertyChangeEvent evt)
            //if ("progress" == evt.getPropertyName()) // *** avoid doing this
            if ("progress".equals(evt.getPropertyName()))
                int progress = (Integer) evt.getNewValue();
                progressBar.setValue(progress);
                System.out.println("progress is: " + progress);
                if (fileSender != null && fileSender.isDone())
                    progressBar.setString("Transfer finished");
                    System.out.println("file sender is done");
                if (fileReceiver != null && fileReceiver.isDone())
                    progressBar.setString("Transfer finished");
                    System.out.println("file receiver is done");
        private class FileReceiver
            public boolean isDone()
                return false;
        private class FileSender extends SwingWorker<Void, Void>
            private int max;
            private int bufferSize;
            int bytesRead;
            int progress = 0;
            public FileSender(int max)
                this.max = max;
                System.out.println("NOTICE: FileSender initialised. ");
                bufferSize = max;
                setProgress(0);
            public Void doInBackground()
                sendFile();
                return null;
            public void sendFile()
                System.out.println("NOTICE: Sending file ");
                System.out.println("Max = " + max);
                bufferSize = 10;
                while (progress < max)
                    try
                        Thread.sleep(100);
                    catch (InterruptedException e)
                        e.printStackTrace();
                    progress += bufferSize;
                    if (progress < max)
                        setProgress(progress);
                    else
                        setProgress(max);
                System.out.println("after while loop");
        private static void createAndShowUI()
            JFrame frame = new JFrame("FileTracker");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
            FileTracker filetracker = new FileTracker(frame);
            filetracker.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }The SwingWorker stops when only 20% of "file transfer" has occurred, but when the progress has reached 100. Then if you go into the [SwingWorker API for setProgress|http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html#setProgress(int)] , you see why the program is stopping here: the SwingWorker stops when its progress property reaches 100. So you must change this to a ratio rather than total bytes.

  • File Copy With JProgressBar

    Hi i'm using the below code to copy a file and display the progress on screen. However the file copies ok by the progressbar is never shown. Can somebody please show me how to use the JProgressBar Component to copy a file and show the progress?
    Thanks
    Arlef
    public void copyFileToMediaFolder(File f){
    String newFileName = f.getName();
    try{
    File inputFile = f.getAbsoluteFile();
    int fSize = (int)f.length();
    FileCopyProgress fcp = new FileCopyProgress(this,true);
    File outputFile = new File(mediaFolder + File.separatorChar + newFileName);
    FileInputStream in = new FileInputStream(inputFile);
    FileOutputStream out = new FileOutputStream(outputFile);
    int c;
    int bytesRead = 0;
    int counter = 0;
    while ((c = in.read()) != -1){
    out.write(c);
    counter = counter + 1;
    bytesRead = fSize / 100 * counter;
    in.close();
    out.close();
    fcp.dispose();
    }catch(Exception ex){
    //System.out.println("nEW FILE NAME = "+newFileName);
    }

    The progressbar is in a JDialog and is represented in
    the following line in the code i sent earlier
    FileCopyProgress fcp = new FileCopyProgress(this,true);Yes, i'm aware of that, but what I'm saying is that you don't seem to be updating the status of the progressbar while copying the file...I suppose the progressbar would start with 0 or 0% and then there should be some functions to be called to make it "progress" to 10..20...50..60% etc... So I believe you should call such a function from inside the loop where the file is being copied...I remember it used to be like that in Visual C++, so i'm supposing the behavior is similar in Java.
    Good luck :)
    Talal

  • Help needed with JProgressBar

    Hi Friends,
    I am creating a java application using swings and i got stuck with JProgressBar. I have a JMentuItem called "PrintReport" in my JFrame. Now when i click the "PrintReport" menuitem i will perform the printing by parsing some xml files.
    i need to show the progress of printing, like when we click on "PrintReport" menuitem a progressbar should appear showing the progress of printing and once the printing is done progressbar should disappear. I have written a JProgressBar and placed the progressbar in JDialog.
    My problem is when i click the "PrintReport" menitem a dialog is appearing showing the progressbar , but unless i close that dialog i am not able to printreport. I am sending code i have written for progressbar.
    Can anyone help me with this problem
    Thankyou
    // This is the method called when i click "PrintReport" menuitem
    public void printReport(String listName) {
          // start printing here      
               listPrinter.startPrint(vn, dt);
          // code for JProgressBar
                JProgressBar progress = new JProgressBar();
                progress.setIndeterminate(true);
                progress.setString("Please Wait...");
                progress.setStringPainted(true);
                JOptionPane.showMessageDialog(frame,progress);
          // Finish printing here
               listPrinter.finishPrint(dl, fname);
               progress.setIndeterminate(false); 
    //  JFrame,JMenuitems, main function are in a different class

    JOptionPane is modal. That means that your application waits until the JOptionPane is closed again. Make your own dialog that shows the same thing.

  • Help with JDialog

    New to Java. I used NetBeans IDE to create program to display a
    JDialog box after a button is pressed. The JDialog should display
    for a period of time and then disappear. Well, the JDialog frame appears,
    but without the contents of the JDialog box (a JProgessBar). Basically,
    all you see is the top of the JDialog box, with the Java logo and JDialog
    title. Any help? Here is the code (the most relevent code is in
    testButtonActionPerformed):
    public class ProgressTest extends javax.swing.JFrame {
        public ProgressTest() {
            initComponents();
        private void initComponents() {
            progressDialog = new javax.swing.JDialog();
            progressBar = new javax.swing.JProgressBar();
            progressTestLabel = new javax.swing.JLabel();
            testButton = new javax.swing.JButton();
            javax.swing.GroupLayout progressDialogLayout = new javax.swing.GroupLayout(progressDialog.getContentPane());
            progressDialog.getContentPane().setLayout(progressDialogLayout);
            progressDialogLayout.setHorizontalGroup(
                progressDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(progressDialogLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(progressBar, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addContainerGap())
            progressDialogLayout.setVerticalGroup(
                progressDialogLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(progressDialogLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            progressTestLabel.setText("Progress Test");
            testButton.setText("Test");
            testButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    testButtonActionPerformed(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(testButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(progressTestLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(progressTestLabel)
                    .addGap(15, 15, 15)
                    .addComponent(testButton)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            pack();
        }// </editor-fold>                       
        private void testButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
            Thread progressThread = new Thread(new Runnable(){
                public void run() {
                    progressDialog.setVisible(true);
            progressThread.start();
            for (int i = 0; i < 10000; i++) {
                System.out.println(i);
            progressDialog.setVisible(false);
         public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ProgressTest().setVisible(true);
        private javax.swing.JProgressBar progressBar;
        private javax.swing.JDialog progressDialog;
        private javax.swing.JLabel progressTestLabel;
        private javax.swing.JButton testButton;
    }

    you'll find a working example in the tutorial
    take the time to read it and learn it
    http://java.sun.com/docs/books/tutorial/uiswing/components/progress.html

  • Tiny problem with a JDialog

    Hi all!
    I'm working on a small application that time.
    My app has a main class which provides the gui components to the user.
    I've built a JDialog with a JProgressBar on it to show the progress of a special process.
    This JDialog is coded in an own class
    public class ProgressDialog {
      JDialog msg;
      public ProgressDialog(JFrame owner) {
        msg = new JDialog(owner);
    }(i solved the integration of the JDialog that indirect way 'cause I was unable to find a method to set the owning Component.
    As far as i instantiate and call that class in my main class's constructor, everything works fine and will be presented as it should be.
    If i create a new instance of "ProgressDialog" outside the constructor (maybe in the method "actionPerformed" that after clicking a button the JDialog will be shown...) it only shows the outer border of the JDialog but nothing more (not even a grey background... you see the main gui-frame which is located behind...)
    maybe there's someone having an idea how to solve my problem and who can tell me how to bring my JDialog - instanciated outside the main-class's constructor - to visible!
    i'm using jdk 1.4
    kind regards,
    thof

    What's going on in your special process?
    It sounds like you are occupying the main Swing thread, and thus keeping it from dealing with the user interface. It sounds like you are going to need to run your special process in a thread, and allow the main Swing thread to keep doing its job.
    Are you making a server call? Or doing a bunch of processing in your app?
    Andrew Wilcox

  • Refresh jProgressBar

    Hi,
    Problem seems to be popular in forums, but i did't find solution in my situation. I have main class which creates thread for second class with JFrame frame.
    public class mainClass
         public static void main(String[] args)
              dialogClass dialogFrame = new dialogClass(null,false);
                 Thread newThread_1 = new Thread(dialogFrame);
                 newThread_1.start();
    }Here is code for second class called from mainClass:
    public class dialogClass extends javax.swing.JDialog implements Runnable, ActionListener
         progressFrame progress; //object of progressFrame
         Thread myThread_2;     //Thread which will be run to update progressBar
         public dialogClass(java.awt.Frame parent, boolean modal)
                 super(parent, modal);
                 initComponents();
                 jButton1.addActionListener(this); //This is for testing purposes
              /**Create object of class which shows JProgressBar.
              * Class progressFrame implements Runnable interface.
                 progress = new progressFrame(null,false);
                 myThread_2 = new Thread(progress);
         // I am working in NetBeans that's why this method
         private void initComponents()
              jButton1 = new JButton("run");
         public void actionPerformed(ActionEvent evt)
                    myThread2.start();
              /* Here is my problem.
              * When user click button, progressBar should be updated in loop
              int i = 0
              //I have made a few tries to resolve my problem
              //1st
              while(i <=10)
                  /** this method is implemented in class with progressBar.
                  * It uses setValue to set value of progressBar
                        progress.updateProgressBar(i);
                        try
                            Thread.sleep(1000);
                        } catch (InterruptedException ex)
                            ex.printStackTrace();
                        i++;
                    System.out.println("Finished");
              //2nd try
              // In this example is use SwingUtilities.invokeLater to update progressBar but it also doesn't work.
              while(i <=10)
                        SwingUtilities.invokeLater(new Runnable()
                            public void run()
                                progress.updateProgressBar(10);
                        try
                            Thread.sleep(1000);
                        } catch (InterruptedException ex)
                            ex.printStackTrace();
                        i++;
    }Somebody knows why this code doesn't work when I put it inside actionPerformed method and (the same code) work great directly inside run() method. Does somebody know how to update progressBar
    inside actionPerformed method. I can't use it inside run() method.
    Peter D.

    I really apreciate for your answer. Method updateProgressBar is responsible for updating (setValue()) progressBar in other thread.
    Thanks for link, but I didn't find situation like mine (updating values inside other thread) in any documentation.
    Thank you again
    Peter D.
    Code correction.
    myThread = new Thread(new Runnable()
                public void run()
                    progress = new progressFrame(null,false,10);
                    Thread myThread2 = new Thread(progress);
                    myThread2.start();
                    System.out.println("actionPerformed currentThread: " + myThread.currentThread().getName());
                    int i = 0;
                    while(i <=10)
                        progress.updateProgressBar(i);
                        try
                            Thread.sleep(1000);
                        } catch (InterruptedException ex)
                            ex.printStackTrace();
                        i++;
                    System.out.println("finished");
            myThread.start();Message was edited by:
    Peter_D

  • Problem with jDialog in a JFrame

    Hello to everyone...i'm newby java GUI developer, and i've got a problem with a JDialog within a JFrame...
    I made a JFrame which creates a new customized JDialog in his contructor, like this:
    MioJdialog dlg = new MioJdialog(this, true);
    dlg.setVisible(true);
    ...The "MioJdialog" class store his JFrame parent under a private attribute, in this way:
    class MioJdialog {...
    private Frame parent;
    public MioJdialog (Frame parent, boolean modal){
        this.parent=parent;
    ....}and here's the problem: when i try to close the parent JFrame with a command like this:
    parent.dispose();
    ( in order to close the whole window), sometimes happens that the JFrame is still visible on the screen...and i don't know why...
    got some hints?
    thanks to everyone!
    Edited by: akyra on Jan 14, 2008 4:36 AM
    Edited by: akyra on Jan 14, 2008 4:37 AM
    Edited by: akyra on Jan 14, 2008 4:37 AM

    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
    http://homepage1.nifty.com/algafield/sscce.html
    Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
    http://forum.java.sun.com/help.jspa?sec=formatting

  • Problem with JDialogs and Threads

    Hi. I'm new to this forum and I hope I'm not asking a repeat question. I didn't find what I needed after a quick search of existing topics.
    I have this problem with creating a new JDialog from within a thread. I have a class which extends JDialog and within it I'm running a thread which calls up another JDialog. My problem is that the JDialog created by the Thread does not seem to function. Everything is unclickable except for the buttons in the titlebar. Is there something that I'm missing out on?

    yeah, bad idea, don't do that.

  • Problem with JDialogs

    Hi All,
    I have a problem with JDialogs in my standalone application. This app pops-up multiple JDialogs, say a stack of JDialogs.
    I have a standalone application which runs as a JFrame, call it JFrame1, which is working fine. JFrame1 pops-up a JDialog, on some button click on JFrame1, call it JDialog1, which is also working fine. Now JDialog1 pops-up another JDialog, again on some button click on JDialog1, call it JDialog2, which is too working fine. But, after I finish with JDialog2 and dispose it my JDialog1 is not working fine, though that is the front dialog at present.
    Any ideas why JDialog1 is not working fine? Am I missing anything?
    Thanks,
    Srinivas.

    Hi,
    I have a component called DateComponent that works similar to a JComboBox. When you click a small button of DateComponent, it pops-up a Calendar similar to the drop down list of JComboBox and user can pick a date from it. It gets closed when it loses focus.
    I have this DateComponent on JFrame1, JDialog1 and JDialog2. The Calendar is not being diaplayed on JDialog1 upon clicking the small button of DateComponent after JDialog2 is disposed. But it is being diaplayed properly on JDialog1 before JDialog1 opens JDialog2. What could be wrong?
    I am using JDK1.3.1.
    Thanks,
    Srinivas.

Maybe you are looking for

  • How do i import my previous website into iWeb?

    I had previously designed my website in iWeb and published it, i then had to wipe my hard drive but backed everything up, now i can't seem to open or import my old website back into iweb, any help please?

  • Video clips are missing from iMovie...Yosemite?

    I recently downloaded Yosemite. I had a number of video clips (from Cannon Camera) in iMovie; they are no longer showing up. These clips were of my deceased mom. I've tried finding them in Time Capsule - NOT there. Can someone PLEASE HELP ME. Thank y

  • WBS assignment in Sales order

    Hi, I wanted to grey out WBS assignement column in sales order for a particular line item once there is any subsequent document created for that. Any suggestion... Cheers !!

  • How to repair in another country?

    Hello! I live in Russian Federation. One year ago (Jan 5, 2012) I've purchased a Nokia Lumia 800 on Ebay from a UK seller. A month ago the phone has refused to charge and (consequently) to power on. I brought it to a local official certified Nokia re

  • What makes a song 'ineligible' for match?

    I have a number of files in my itunes library which are not uploaded to itunes match. They are all labled 'ineligible'. Are there certain types of recordings i.e. aiff, mp3, Sd2f which are not uploadable? What can I do to make them 'eligible'?