简体   繁体   English

JProgressBar不更新

[英]JProgressBar does not update

I am having problems with the JprogressBar 'pb1' - it will not update. 我在JprogressBar'pb1'上遇到问题-它不会更新。 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. 我不确定,propertyChangeListener可能有问题。

   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);
        }
    });
}
}

You never appear to call setProgress(...) inside of your Task SwingWorker. 您似乎从未在Task SwingWorker内部调用setProgress(...) If the progress property never changes, then calling getProgress() will not show any changes. 如果progress属性从不更改,则调用getProgress()将不会显示任何更改。

To solve this, you must rig your doInBackGround to call setProgress(...) as things are progressing. 为了解决这个问题,必须在事情进行过程中装配doInBackGround来调用setProgress(...) This will notify any PropertyChangeListeners that are listening to the worker. 这将通知正在监听工作程序的所有PropertyChangeListener。 You would likely do this inside of the while loop where you process the file. 您可能会在处理文件的while循环内执行此操作。


As an aside, you have another dangerous SwingWorker that appears to be making Swing calls, such as setText(null) from withn the doInBackground() method: 顺便说doInBackground() ,您还有另一个危险的SwingWorker似乎正在执行Swing调用,例如使用doInBackground()方法从setText(null)进行调用:

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. 您不想这样做,请从EDT发起Swing呼叫。 In fact I see no reason to use a SwingWorker at this spot in your code and many reasons not to. 实际上,我认为您的代码中没有理由在此位置使用SwingWorker,并且有很多理由不这样做。


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 . 下次在这里,请减少代码,只需将代码分解为可管理的,可以编译,运行并显示问题的代码sscce即可

Updating the JprogressBar in your case will depend on the length of the task. 根据您的情况,更新JprogressBar将取决于任务的长度。 Instead of using pb1.setStringPainted(true); 而不是使用pb1.setStringPainted(true); you could use pb1.setIndeterminate(true); 您可以使用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. 它不会显示您已完成任务的确切百分比,但是会允许JProgressBar表示任务在任务期间仍在处理中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM