Java进度条没有进展,尽管文件已下载?

Java进度条没有进展,尽管文件已下载?,java,swing,download,event-dispatch-thread,jprogressbar,Java,Swing,Download,Event Dispatch Thread,Jprogressbar,我在这个论坛上访问了和其他几个类似的页面,并在Oracle文档上浏览了Swing。他们的所有代码都不适用于我的ProgressBar,即使我逐行模拟他们的所有代码,并对代码进行一些调整。我不知道为什么它不起作用!我真的很可怜我自己,我不能让它工作 我知道EDT有一些问题,但我自己无法解决。我想我的代码正在工作线程上更新进度条 此外,代码下载时,如果我再次重置字段和所选项目,则后续的下载调用也会被阻止。文件已创建,但未下载。它们的大小仍然是0。请解释一下原因 我创建了一个SwingWorker实例

我在这个论坛上访问了和其他几个类似的页面,并在Oracle文档上浏览了Swing。他们的所有代码都不适用于我的ProgressBar,即使我逐行模拟他们的所有代码,并对代码进行一些调整。我不知道为什么它不起作用!我真的很可怜我自己,我不能让它工作

  • 我知道EDT有一些问题,但我自己无法解决。我想我的代码正在工作线程上更新进度条

  • 此外,代码下载时,如果我再次重置字段和所选项目,则后续的下载调用也会被阻止。文件已创建,但未下载。它们的大小仍然是0。请解释一下原因

  • 我创建了一个SwingWorker实例,并从doInBackground()方法调用了FileProgressBar的更新,然后调用done()。但是,它不起作用。文件下载成功,但是进度条没有移动一英寸

    public class Client{ 
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new MakeGUI().setVisible(true);
            }
        });
                }
     }
    
    class MakeGUI extends JFrame implements PropertyChangeListener{
    private JTextField ClientNameTF;
    private JLabel DisplayLabel;
    private JButton DownloadButton;
    private JButton ExitButton;
    private JComboBox FileComboBox;
    private JProgressBar FileProgressBar;
    private JButton FileStatusButton;
    private JLabel FinalLabel;
    private JTextField StatusTextField;
    private JLabel TitleLabel;
    private JButton ResetButton;
    private JLabel LoginLabel;
    private ProgressWorker pw;
    private static JFrame jf;
    public static String IP_ADDRESS_TO_CONNECT;
    
    public MakeGUI() {
        FileComboBox = new javax.swing.JComboBox();
        DisplayLabel = new javax.swing.JLabel();
        FileStatusButton = new javax.swing.JButton();
        StatusTextField = new javax.swing.JTextField();
        DownloadButton = new javax.swing.JButton();
        FileProgressBar = new javax.swing.JProgressBar();
        ExitButton = new javax.swing.JButton();
        FinalLabel = new javax.swing.JLabel();
        TitleLabel = new javax.swing.JLabel();
        LoginLabel = new javax.swing.JLabel();
        ClientNameTF = new javax.swing.JTextField();
        ResetButton = new javax.swing.JButton();
        callPainting();
    }
    
    public void callPainting(){
        setLocationRelativeTo(null);
        setBounds(300, 0, 300, 300);
        FileComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "ALGORITHM- The Hacker.MKV", "ARUN_ASAD.docx", "Johnny Sins.jpg", "MGH.Java.The.Complete.Reference.9th.Edition.pdf", "rabbit4.11-src.tar.gz", "SAMUDRA.jpg", "Syngress - Seven Deadliest Web Application Attacks (2010) (ATTiCA).pdf", "Tu Hai Ki Nahi (Roy).mp3" }));
    
        FinalLabel.setLabelFor(FinalLabel);
    
        TitleLabel.setText("Distributed File Downloading System");
    
        LoginLabel.setText("Your Login Name");
    
        DisplayLabel.setText("Select the Item you wanna download");
    
        FileStatusButton.setText("Check Status of the File");
        FileStatusButton.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FileStatusButtonActionPerformed(evt);
            }
        });
    
        DownloadButton.setText("Start Download");
        DownloadButton.setEnabled(false);
        DownloadButton.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DownloadButtonActionPerformed(evt);
            }
        });
    
        FileProgressBar.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(187, 55, 55)));
        FileProgressBar.setStringPainted(true);
        FileProgressBar.setMinimum(0);
        FileProgressBar.setMaximum(100);
        FileProgressBar.setValue(0);
        //FileProgressBar.setIndeterminate(false);
    
        ResetButton.setText("Reset");
        ResetButton.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ResetButtonActionPerformed(evt);
            }
        });
    
        ExitButton.setText("Exit Application");
        ExitButton.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ExitButtonActionPerformed(evt);
            }
        });
        pack();
    }
    
    public void FileStatusButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        try {
            String clientName=ClientNameTF.getText();
            int choiceOfFile = FileComboBox.getSelectedIndex();
            new Server().requestFile(choiceOfFile,clientName);
            IP_ADDRESS_TO_CONNECT=new Server().returnIPAddress();
            StatusTextField.setText("Server Available = "+IP_ADDRESS_TO_CONNECT);
            if(!(StatusTextField.getText().isEmpty()))
                DownloadButton.setEnabled(true);
            else
                DownloadButton.setEnabled(false);
        } catch (IOException ex) {
            FinalLabel.setText(ex.getMessage());
        }
    }
    
    public void DownloadButtonActionPerformed(java.awt.event.ActionEvent evt)  {
        DownloadButton.setEnabled(false);
        boolean COMPLETION=false;   
        long fsize=new Server().returnFileSize();
        String fileSize;
        Long initialTime = 0L;
        if(fsize <= 0) {
            fileSize = "0";
        }
        final String[] units = new String[] { "B", "kB", "MB", "GB", "TB" };
        int digitGroups = (int) (Math.log10(fsize)/Math.log10(1024));
        fileSize= new DecimalFormat("#,##0.#").format(fsize/Math.pow(1024, digitGroups)) + " " + units[digitGroups];               
        String choiceOfFile = (String)FileComboBox.getSelectedItem();
        int dialogButton=JOptionPane.YES_NO_OPTION;
        if(new File(choiceOfFile).exists()){
            int dialogResult=JOptionPane.showConfirmDialog(null,"Would you like to delete your already"
                    + " existing file(Press Yes to delete OR No to quit)???","Confirm Action", dialogButton);
            if(dialogResult==JOptionPane.YES_OPTION){
                new File(choiceOfFile).delete();
            }
            else {
                FinalLabel.setText("File Already Exists!!! If you wish, you can download some another file...");
                System.exit(-1);
            }
        }
       FinalLabel.setText("File Size to be Downloaded = "+fileSize);   
       ProgressWorker pw = new ProgressWorker(choiceOfFile,IP_ADDRESS_TO_CONNECT,fsize);
       initialTime = System.nanoTime();
       pw.addPropertyChangeListener(this);
                       /*else if (name.equals("state")) {
                                SwingWorker.StateValue state = (SwingWorker.StateValue)evt.getNewValue();
                                switch (state) {
                                    case DONE : 
                                {
                                    DownloadButton.setEnabled(true);
                                        break;
                                }        
                                }
                            }*/
       pw.execute();
                try {
                    initialTime = pw.get();
                } catch (InterruptedException | ExecutionException ex) {
                    ex.printStackTrace();
                }
        long finalTime=System.nanoTime(); 
        float difference = (float)((finalTime-initialTime)/1000000000.0);
        StatusTextField.setText("Time difference = "+difference);
        }
    
    public void ResetButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
            ClientNameTF.setText("");
            StatusTextField.setText("");
            FinalLabel.setText("");
            FileComboBox.setSelectedIndex(0);
            FileProgressBar.setValue(0);
    } 
    
    public void ExitButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
            int response = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit this application?", "Confirm",
            JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if (response == JOptionPane.NO_OPTION) {
            System.out.println("No button clicked");
            } else if (response == JOptionPane.YES_OPTION) {
                System.exit(0);
            } else if (response == JOptionPane.CLOSED_OPTION) {
             System.out.println("JOptionPane closed");
            }        
    } 
    
    @Override
    public void propertyChange(PropertyChangeEvent evt) {
       if("progress" == evt.getPropertyName()){
           int progress = (Integer)evt.getNewValue();
           FileProgressBar.setValue(progress);
       }
    }
    
    class ProgressWorker extends SwingWorker<Long,Integer>{
    String cof,IP;
    long fileSize;
    Long initialTime;
    File downloadingFile;
    
    public ProgressWorker(String choiceOfFile,String IP_ADDRESS_TO_CONNECT,long fsize) {
        this.cof = choiceOfFile;
        this.IP = IP_ADDRESS_TO_CONNECT;
        this.fileSize = fsize;
        downloadingFile = new File("/home/you/Desktop/BASH/Client",cof);
    }
    
    @Override
    public Long doInBackground() throws Exception {
        int temp=1;
        boolean flag=true;
        int progressPercent = 0;
        setProgress(progressPercent);
        initialTime=System.nanoTime();
        if(SwingUtilities.isEventDispatchThread()==true)
            System.out.println("True EDT.");
        else
            System.out.println("Worker Threads...");
        StartFileClient.startDownloading(cof,IP);     
        while(progressPercent<100 && downloadingFile.length() != fileSize){
            //System.out.println("Length = "+downloadingFile.length());
            progressPercent = (int)((downloadingFile.length()*100.0)/fileSize);
            setProgress(progressPercent);
            Thread.sleep(50);
        }
        return initialTime;
    }
    
    @Override
    public void done(){
        Toolkit.getDefaultToolkit().beep();
        DownloadButton.setEnabled(true);
        FinalLabel.setText("Downloading Done...");
    }
    
    }
    
    }
    
    公共类客户端{
    公共静态void main(字符串[]args){
    SwingUtilities.invokeLater(新的Runnable(){
    @凌驾
    公开募捐{
    新建MakeGUI().setVisible(true);
    }
    });
    }
    }
    类MakeGUI扩展JFrame实现PropertyChangeListener{
    私有JTextField ClientNameTF;
    专用JLabel显示标签;
    私人JButton下载按钮;
    私有JButton ExitButton;
    私有JComboBox文件组合框;
    私有JProgressBar文件ProgressBar;
    私有JButton文件statusbutton;
    私人JLabel FinalLabel;
    私有JTextField StatusTextField;
    私人JLabel TitleLabel;
    私有JButton重置按钮;
    私人JLabel LoginLabel;
    私人工人;
    私有静态jf帧;
    公共静态字符串IP地址连接;
    公共MakeGUI(){
    FileComboBox=newjavax.swing.JComboBox();
    DisplayLabel=newjavax.swing.JLabel();
    FileStatusButton=newjavax.swing.JButton();
    StatusTextField=newjavax.swing.JTextField();
    DownloadButton=newjavax.swing.JButton();
    FileProgressBar=newjavax.swing.JProgressBar();
    ExitButton=newjavax.swing.JButton();
    FinalLabel=newjavax.swing.JLabel();
    TitleLabel=newjavax.swing.JLabel();
    LoginLabel=newjavax.swing.JLabel();
    ClientNameTF=newjavax.swing.JTextField();
    ResetButton=newjavax.swing.JButton();
    callPainting();
    }
    公共绘画({
    setLocationRelativeTo(空);
    立根(300,0,300,300);
    FileComboBox.setModel(新的javax.swing.DefaultComboBoxModel(新的字符串[]{“ALGORITHM-The Hacker.MKV”、“ARUN_ASAD.docx”、“Johnny Sins.jpg”、“MGH.Java.The.Complete.Reference.9th.Edition.pdf”、“rabbit4.11-src.tar.gz”、“SAMUDRA.jpg”、“Syngress-Seven Deadlest Web应用程序攻击(2010)”(ATTiCA.pdf)、“Tu Hai Ki Nahi(Roy.mp3”);
    FinalLabel.setLabelFor(FinalLabel);
    TitleLabel.setText(“分布式文件下载系统”);
    LoginLabel.setText(“您的登录名”);
    DisplayLabel.setText(“选择要下载的项目”);
    setText(“检查文件状态”);
    FileStatusButton.addActionListener(新java.awt.event.ActionListener(){
    @凌驾
    public void actionPerformed(java.awt.event.ActionEvent evt){
    执行的文件状态按钮(evt);
    }
    });
    DownloadButton.setText(“开始下载”);
    DownloadButton.setEnabled(错误);
    DownloadButton.addActionListener(新java.awt.event.ActionListener(){
    @凌驾
    public void actionPerformed(java.awt.event.ActionEvent evt){
    下载按钮执行(evt);
    }
    });
    setboorder(javax.swing.BorderFactory.createMatteBorder(1,1,1,1,new java.awt.Color(187,55,55));
    FileProgressBar.SetStringPaint(true);
    FileProgressBar.setMinimum(0);
    FileProgressBar.setMaximum(100);
    FileProgressBar.setValue(0);
    //FileProgressBar.SetUndeterminate(false);
    ResetButton.setText(“重置”);
    ResetButton.addActionListener(新java.awt.event.ActionListener(){
    @凌驾
    public void actionPerformed(java.awt.event.ActionEvent evt){
    执行重置按钮操作(evt);
    }
    });
    setText(“退出应用程序”);
    ExitButton.addActionListener(新java.awt.event.ActionListener(){
    @凌驾
    public void actionPerformed(java.awt.event.ActionEvent evt){
    ExitButtoActionExecuted(evt);
    }
    });
    包装();
    }
    public void FileStatusButtonActionPerformed(java.awt.event.ActionEvent evt){
    试一试{
    字符串clientName=ClientNameTF.getText();
    int choiceOfFile=FileComboBox.getSelectedIndex();
    新建服务器().requestFile(choiceOfFile,clientName);
    IP_地址_TO_CONNECT=新服务器();
    StatusTextField.setText(“服务器可用=“+IP地址到连接”);
    如果(!(StatusTextField.getText().isEmpty())
    DownloadButton.setEnabled(真);
    其他的
    DownloadButton.setEnabled(错误);
    }捕获(IOEX异常){
    FinalLabel.setText(例如getMessage());
    }
    }
    public void DownloadButtonActionPerformed(java.awt.event.ActionEvent evt){
    DownloadButton.setEnabled(错误);
    布尔完成=假;
    long fsize=new Server().returnFileSize();
    字符串文件大小;
    长初始时间=0升;
    
    if(fsize以便更快地获得更好的帮助,发布or.MCVE需要:1)是一个源文件(可能包含多个类,但仅包含一个
    public
    class)。2)包含导入。3)包含
    main(String[])
    方法来运行它。--不可编译的代码段不能成为运行时问题的MCVE。“我不能再让它变短了……”这不是让它变短,或者更简单。而是让它变成C、V和E。你确定
    StartFileClient.startDownloading(cof、IP)<