Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java:使用JSch SFTP在TextArea/JProgressBar中实时更新上传进度_Java_Swing_Ssh_Jsch - Fatal编程技术网

java:使用JSch SFTP在TextArea/JProgressBar中实时更新上传进度

java:使用JSch SFTP在TextArea/JProgressBar中实时更新上传进度,java,swing,ssh,jsch,Java,Swing,Ssh,Jsch,我有两个类fil upload.java和transferProgress.java。java制作小程序GUI并将文件上载到远程SSH服务器。java类给出了传输百分比。上传完成的百分比可以在控制台中看到,但我希望它可以在TextArea和java进度条上看到。所以我让transferProgress.java继承upload.java并附加到TextArea 我的问题是,TextArea和JProgressBar在文件传输过程中不会得到更新,但只有在文件传输完成时才会得到更新。传输完成后,Te

我有两个类fil upload.java和transferProgress.java。java制作小程序GUI并将文件上载到远程SSH服务器。java类给出了传输百分比。上传完成的百分比可以在控制台中看到,但我希望它可以在TextArea和java进度条上看到。所以我让transferProgress.java继承upload.java并附加到TextArea

我的问题是,TextArea和JProgressBar在文件传输过程中不会得到更新,但只有在文件传输完成时才会得到更新。传输完成后,TextArea显示日志,JProgressBar设置为100%。我的代码在文件传输期间不会更新TextArea和JProgressBar

如果我使用setText()而不是append来更新TextArea,我可以看到实时进度更新,但ProgressBar仍然不能实时更新

我想不出问题出在哪里。我将非常感谢你的帮助

upload.java

package biforce;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*; 
import java.io.*; 


import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;


public class upload extends Applet
{

  String filename;
  int port = 22;
  String user = "root";
  String password = "mypass";
  String host = "192.168.0.5";
  String knownHostsFile = "/home/bishwo/.ssh/known_hosts";
  String sourcePath = "";
  String destPath = "/media/dfs/gwas/";

  JTextField txtField = new JTextField(20);
  static TextArea txtArea;
  static JProgressBar progressBar;

    @Override
  public void init(){

  // text Field     
  txtField.setEditable(false);
  txtField.setText("");

  // text area
  txtArea = new TextArea(4,40);
  txtArea.setEditable(false);

  // JprogressBar
  progressBar = new JProgressBar(0, 100);
  progressBar.setValue(0);
  progressBar.setStringPainted(true);

  // Label
  JLabel fileLabel = new JLabel("File");

  // buttons
  JButton upload = new JButton( "Upload" );
  JButton browse = new JButton( "Browse" );

  // browse file to be uploaded
  browse.addActionListener( 
      new ActionListener()
      {
            @Override
        public void actionPerformed( ActionEvent ae )
        {
          JFileChooser fc = new JFileChooser();
          fc.setCurrentDirectory( new File( "/home/bishwo/Desktop/" ) );
          int returnVal = fc.showOpenDialog( upload.this ); 
          String filePath="";
          if ( returnVal == JFileChooser.APPROVE_OPTION )   
          {  
            File aFile = fc.getSelectedFile();  
            filePath = aFile.getAbsolutePath(); 
            filename = aFile.getName();
          }
          txtField.setText(filePath);
        }
      });
  // upload the browsed file
  upload.addActionListener( 
      new ActionListener()
      {
            @Override
        public void actionPerformed( ActionEvent ae )
        {

          if(txtField.getText().length()==0)
          {
              JOptionPane.showMessageDialog(upload.this,"Please select a file to upload.","Error", JOptionPane.ERROR_MESSAGE);
          }
          else
          {
            try
            {
                sourcePath=txtField.getText();
                JSch jsch = new JSch();
                jsch.setKnownHosts(knownHostsFile);
                Session session = jsch.getSession(user, host, port);
                session.setPassword(password);
                session.connect(); 

                ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
                sftpChannel.connect();

                txtArea.setText("Uploading..");
                transferProgress progress = new transferProgress();
                sftpChannel.put( sourcePath,destPath+filename, progress);      
                System.out.println("\nUpload Completed");  

                sftpChannel.exit();
                session.disconnect();
                JOptionPane.showMessageDialog(upload.this,"Upload completed successfully.","Info", JOptionPane.INFORMATION_MESSAGE);

            }
            catch(Exception e)
            {
                JOptionPane.showMessageDialog(upload.this,e,"Error", JOptionPane.ERROR_MESSAGE);
            }
          }
        }
      });

  add(fileLabel);
  add(txtField,"center");
  add(browse);
  add(upload);
  add(progressBar);
  add(txtArea);
  }

}
import com.jcraft.jsch.*;

public class transferProgress extends upload implements SftpProgressMonitor
{
    public double count=0;
    private int percentage;
    public double totalSize;
    private int lastPercentage;
    @Override
    public void init(int op, String src, String dest, long max) 
        {
        this.totalSize=max;
        }

    @Override
    public boolean count(long count) 
        {
        this.count += count;
        this.percentage = (int) ((this.count / this.totalSize) * 100.0);
        if (this.lastPercentage <= this.percentage - 5) 
            {
            this.lastPercentage= this.percentage;
            // setValue() does not work
            biforce.upload.progressBar.setValue(20);
            // append() does not work
            biforce.upload.txtArea.append(Integer.toString(this.percentage));
            // displays percentage completion on console
            System.out.println("Upload Completion "+this.percentage+" %");

            }
        return true;
        }

    @Override
    public void end() 
        {
        System.out.println("Total Copied "+this.percentage+" %");
        }
}
transferProgress.java

package biforce;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*; 
import java.io.*; 


import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;


public class upload extends Applet
{

  String filename;
  int port = 22;
  String user = "root";
  String password = "mypass";
  String host = "192.168.0.5";
  String knownHostsFile = "/home/bishwo/.ssh/known_hosts";
  String sourcePath = "";
  String destPath = "/media/dfs/gwas/";

  JTextField txtField = new JTextField(20);
  static TextArea txtArea;
  static JProgressBar progressBar;

    @Override
  public void init(){

  // text Field     
  txtField.setEditable(false);
  txtField.setText("");

  // text area
  txtArea = new TextArea(4,40);
  txtArea.setEditable(false);

  // JprogressBar
  progressBar = new JProgressBar(0, 100);
  progressBar.setValue(0);
  progressBar.setStringPainted(true);

  // Label
  JLabel fileLabel = new JLabel("File");

  // buttons
  JButton upload = new JButton( "Upload" );
  JButton browse = new JButton( "Browse" );

  // browse file to be uploaded
  browse.addActionListener( 
      new ActionListener()
      {
            @Override
        public void actionPerformed( ActionEvent ae )
        {
          JFileChooser fc = new JFileChooser();
          fc.setCurrentDirectory( new File( "/home/bishwo/Desktop/" ) );
          int returnVal = fc.showOpenDialog( upload.this ); 
          String filePath="";
          if ( returnVal == JFileChooser.APPROVE_OPTION )   
          {  
            File aFile = fc.getSelectedFile();  
            filePath = aFile.getAbsolutePath(); 
            filename = aFile.getName();
          }
          txtField.setText(filePath);
        }
      });
  // upload the browsed file
  upload.addActionListener( 
      new ActionListener()
      {
            @Override
        public void actionPerformed( ActionEvent ae )
        {

          if(txtField.getText().length()==0)
          {
              JOptionPane.showMessageDialog(upload.this,"Please select a file to upload.","Error", JOptionPane.ERROR_MESSAGE);
          }
          else
          {
            try
            {
                sourcePath=txtField.getText();
                JSch jsch = new JSch();
                jsch.setKnownHosts(knownHostsFile);
                Session session = jsch.getSession(user, host, port);
                session.setPassword(password);
                session.connect(); 

                ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
                sftpChannel.connect();

                txtArea.setText("Uploading..");
                transferProgress progress = new transferProgress();
                sftpChannel.put( sourcePath,destPath+filename, progress);      
                System.out.println("\nUpload Completed");  

                sftpChannel.exit();
                session.disconnect();
                JOptionPane.showMessageDialog(upload.this,"Upload completed successfully.","Info", JOptionPane.INFORMATION_MESSAGE);

            }
            catch(Exception e)
            {
                JOptionPane.showMessageDialog(upload.this,e,"Error", JOptionPane.ERROR_MESSAGE);
            }
          }
        }
      });

  add(fileLabel);
  add(txtField,"center");
  add(browse);
  add(upload);
  add(progressBar);
  add(txtArea);
  }

}
import com.jcraft.jsch.*;

public class transferProgress extends upload implements SftpProgressMonitor
{
    public double count=0;
    private int percentage;
    public double totalSize;
    private int lastPercentage;
    @Override
    public void init(int op, String src, String dest, long max) 
        {
        this.totalSize=max;
        }

    @Override
    public boolean count(long count) 
        {
        this.count += count;
        this.percentage = (int) ((this.count / this.totalSize) * 100.0);
        if (this.lastPercentage <= this.percentage - 5) 
            {
            this.lastPercentage= this.percentage;
            // setValue() does not work
            biforce.upload.progressBar.setValue(20);
            // append() does not work
            biforce.upload.txtArea.append(Integer.toString(this.percentage));
            // displays percentage completion on console
            System.out.println("Upload Completion "+this.percentage+" %");

            }
        return true;
        }

    @Override
    public void end() 
        {
        System.out.println("Total Copied "+this.percentage+" %");
        }
}
import com.jcraft.jsch.*;
公共类transferProgress扩展上载实现SFTProgressMonitor
{
公共重复计数=0;
私人机构的int百分比;
公共部门的总规模增加一倍;
私人股本占总股本的百分比;
@凌驾
public void init(int op、String src、String dest、long max)
{
这个。totalSize=max;
}
@凌驾
公共布尔计数(长计数)
{
this.count+=计数;
this.percentage=(int)((this.count/this.totalSize)*100.0);

如果(this.lastPercentage您需要在单独的线程中更新progressbar

我建议让您的类
transferProgress
(注意:类名称应以大写字母开头)实现,然后使用来启动该类的新线程

例如


您永远不应该从事件调度线程(EDT)执行长时间运行的操作,因为GUI在此期间被阻塞。您在这里观察到了这种情况的影响。 EDT是一个线程,它运行所有动作监听器,并重新绘制GUI对象。只要动作监听器正在运行,就不会调度其他事件,也不会发生绘制=>您将不会在进度栏或文本区域上看到任何更新。(不过,一旦动作监听器完成,它们将被更新。)

因此,使用一个单独的线程上传文件,即ActionListener中
else
-块中的所有内容,如flash的答案

然后,所有更新GUI的操作都应该在EDT中再次完成,因此使用
EventQueue.invokeLater
(或
SwingUtilities.invokeLater
)作为GUI更新部分:

EventQueue.invokeLater(new Runnable() { public void run() {
       biforce.upload.progressBar.setValue(20);
       biforce.upload.txtArea.append(Integer.toString(this.percentage));
}});
transferProgress类中的count()方法在上传文件之前提供20倍的进度百分比

在我的例子中,SwingUtilities.invokeLater不起作用。我使用了SwingWorker,从upload类执行,它起作用了。 (附言-我让progressBar在课堂上传“public”)

公共类uploadWorker扩展SwingWorker
{
@凌驾
受保护的整数doInBackground()引发异常
{
//一些代码。。。。。
请尝试{sftpChannel.put(upload.sourcePath,upload.destPath,new transferProgress());}
catch(异常e){System.out.println(e);}
睡眠(1000);
返回42;
}
受保护的void done()
{
系统输出打印(“完成”);
}
}

不是最基本的问题:不要混合使用AWT和Swing组件请学习java命名约定并遵守它们