Question

I am having problems with the JprogressBar 'pb1' - it will not update. I have tried different approaches to make it work but it seems I can not find where am I going wrong. There might be an issue with the propertyChangeListener, I am not entirely sure.

   package one;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

import java.beans.*;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.swing.*;

public class ProgressBar extends JFrame implements ActionListener, PropertyChangeListener {

    private JButton searchBtn;
    private JButton displayBtn;
    private JButton reverseBtn;
    private JButton ZIPbtn;
    private JLabel lblPath;
    private JLabel lblTxt1;
    private JLabel lblTxt3;
    private JLabel lblTxt2;
    private JTextArea txt1;
    private JScrollPane txtP1;
    private JTextArea txt2;
    private JScrollPane txtP2;
    private JTextArea txt3;
    private JScrollPane txtP3;
    private JProgressBar pb1;
    private JProgressBar pb2;
    private JProgressBar pb3;

    private Task task;
    static File fileArray;


    class Task extends SwingWorker<Void, Void> {

        BufferedWriter bwr1 = null;
        BufferedReader br1w = null;

        @Override
        protected Void doInBackground()
                throws Exception {

            txt1.setText(null);
            bwr1 = new BufferedWriter(
                    new FileWriter(
                            new File(
                                    "C:\\Users\\Saint\\Documents\\file 1 - reversed.txt")));

            BufferedReader br1 = new BufferedReader(
                    new FileReader(fileArray));
            String line;
            while ((line = br1.readLine()) != null) {
                StringBuffer sb1 = new StringBuffer(br1
                        .readLine());
                sb1.reverse();

                bwr1.write(sb1.toString());
            }

            bwr1.flush();

            bwr1.close();

            br1.close();

            System.out
                    .println("Content of StringBuffer written to File 1.");

            br1w = new BufferedReader(
                    new FileReader(
                            "C:\\Users\\Saint\\Documents\\file 1 - reversed.txt"));

            txt1.read(br1w,
                    "C:\\Users\\Saint\\Documents\\file 1 - reversed.txt");

            return null;
        }

        protected void done() {

            Toolkit.getDefaultToolkit().beep();
            reverseBtn.setEnabled(true);
            setCursor(null); //turn off the wait cursor
            pb1.setValue(100);
            pb1.setVisible(false);
        }

    };

    public void actionPerformed(ActionEvent evt) {
        pb1.setStringPainted(true);
        pb1.setVisible(true);

        reverseBtn.setEnabled(false);
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        task = new Task();
        task.addPropertyChangeListener(this);
        task.execute();
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
            int progress = task.getProgress();
            pb1.setValue(progress);
            System.out.println(progress);


    }

public ProgressBar(){

        // construct components
                searchBtn = new JButton("Search");
                reverseBtn = new JButton("Reverse Text");
                reverseBtn.setActionCommand("start");
                reverseBtn.addActionListener(this);
                lblTxt1 = new JLabel("File 1");

                txt1 = new JTextArea(5, 5);
                txtP1 = new JScrollPane(txt1);
                txt1.setLineWrap(true);

                pb1 = new JProgressBar(0, 100);


                txtP1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);


                setSize(new Dimension(800, 800));
                setLayout(null);
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                setTitle("");


                setResizable(false);
                pb1.setVisible(false);
                // pb1.setStringPainted(true);

                // add components
                add(searchBtn);

                add(reverseBtn);

                add(lblTxt1);

                add(txtP1);

                add(pb1);


                // set component bounds (only needed by Absolute Positioning)
                searchBtn.setBounds(15, 15, 100, 25);

                lblTxt1.setBounds(5, 50, 300, 25);

                txtP1.setBounds(5, 75, 735, 190);

                reverseBtn.setBounds(300, 730, 150, 25);

                pb1.setBounds(305, 47, 400, 25);




        searchBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        try {
                            fileChooser();
                            lblTxt1.setText(fileArray.toString());

                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });

    }


private String fileChooser() throws FileNotFoundException {
    // Create a file chooser
    JFileChooser fc = new JFileChooser();
    // Button click response:
    int returnVal = fc.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        fileArray = fc.getSelectedFile();


    } else {
        return "No file selected";
    }
    return "No file selected";
}


public static void main(String[] args) {

    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new ProgressBar().setVisible(true);
        }
    });
}
}
Was it helpful?

Solution

You never appear to call setProgress(...) inside of your Task SwingWorker. If the progress property never changes, then calling getProgress() will not show any changes.

To solve this, you must rig your doInBackGround to call setProgress(...) as things are progressing. This will notify any PropertyChangeListeners that are listening to the worker. You would likely do this inside of the while loop where you process the file.


As an aside, you have another dangerous SwingWorker that appears to be making Swing calls, such as setText(null) from withn the doInBackground() method:

SwingWorker<Void, Void> workerClear = new SwingWorker<Void, Void>() {

  @Override
  protected Void doInBackground() throws Exception {

     txt1.setText(null);
     txt2.setText(null);
     txt3.setText(null);

     return null;
  }
};

You don't want to do this, make Swing calls off of the EDT. In fact I see no reason to use a SwingWorker at this spot in your code and many reasons not to.


Also, and again as per my comment, you are posting too much code unrelated to your problem. Next time here, please post less code by whittling your code down to a manageable amount of code that compiles, runs, and shows your problem, an sscce.

OTHER TIPS

Updating the JprogressBar in your case will depend on the length of the task. Instead of using pb1.setStringPainted(true); you could use pb1.setIndeterminate(true);. It will not show you the exact percentage of the task completed, but will allow the JProgressBar to signify that the task is still in process for the duration of task.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top