2

2つのクラスファイルupload.javatransferProgress.javaがあります。upload.javaはアプレットGUIを作成し、ファイルをリモートSSHサーバーにアップロードします。transferProgress.javaクラスは、転送パーセンテージを提供します。完了したアップロードの割合はコンソールで確認できますが、TextAreaとJavaプログレスバーで確認したかったのです。そこで、transferProgress.javaを作成してupload.javaを継承し、 TextAreaに追加しました。

私の問題は、TextAreaJProgressBarがファイル転送中に更新されないが、ファイル転送が完了したときにのみ更新されることです。転送が完了すると、TextAreaにログが表示され、JProgressBarが100%に設定されます。私のコードは、ファイル転送中にTextAreaJProgressBarを更新しません。

TextAreaを更新するためにappendの代わりにsetText()を使用すると、リアルタイムの進行状況の更新を確認できますが、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);
  }

}

transferProgress.java

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+" %");
        }
}
4

3 に答える 3

1

別のスレッドでプログレスバーを更新する必要があります。

transferProgressクラス(注:クラス名は大文字で始める必要があります)にRunnableインターフェイスを実装させてから、 ExecutorServiceを使用してこのクラスで新しいスレッドを開始することをお勧めします。

例えば

public class TransferProgress extends upload implements SftpProgressMonitor, Runnable {
    @Override
    public void run() {
       //update your progressbar here, basically the same as your count method
    }
}

public class upload extends Applet {
    //some code...
    upload.addActionListener( 
      new ActionListener()
       {
             @Override
             public void actionPerformed( ActionEvent ae )
             {
                 //some code....
                 //start a new thread here which executes your run method in the TransferProgress class
                 ExecutorService executor = Executors.newSingleThreadExecutor();
                 executor.submit(new TransferProgress());
                 //some code...
             }
       }
    );

}
于 2011-11-07T09:06:34.487 に答える
0

この間、GUIはブロックされるため、イベントディスパッチスレッド(EDT)から長時間実行するアクションを実行しないでください。あなたはここでこれの効果を観察しました。EDTは、すべてのアクションリスナーを実行し、GUIオブジェクトを再描画するスレッドです。アクションリスナーが実行されている限り、他のイベントはディスパッチされず、ペイントも発生しません=>プログレスバーまたはテキスト領域に更新は表示されません。(ただし、アクションリスナーが終了すると更新されます。)

したがって、別のスレッドを使用してファイルをアップロードします。つまりelse、フラッシュの回答のように、ActionListenerの-block内のすべてをアップロードします。

GUIを更新するものはすべて、EDTで再度実行する必要があるため、GUIの更新部分にはEventQueue.invokeLater(または)を使用します。SwingUtilities.invokeLater

EventQueue.invokeLater(new Runnable() { public void run() {
       biforce.upload.progressBar.setValue(20);
       biforce.upload.txtArea.append(Integer.toString(this.percentage));
}});
于 2011-11-07T12:32:40.253 に答える
0

transferProgressクラスのcount()メソッドは、ファイルがアップロードされるまで、進行状況のパーセンテージを20回与えます。

私の場合、SwingUtilities.invokeLaterは機能しませんでした。アップロードクラスから実行されたSwingWorkerを使用しましたが、機能しました。(PS-クラスアップロード'public'でprogressBarを作成しました)

public class uploadWorker extends SwingWorker<Integer, Integer>
{
    @Override
        protected Integer doInBackground() throws Exception
        {
                //some codes .....

                try{sftpChannel.put(upload.sourcePath,upload.destPath, new transferProgress()); }
               catch(Exception e){System.out.println(e);}

                Thread.sleep(1000);
                return 42;
        }

        protected void done()
        {

                System.out.print("done");

        }
}
于 2011-11-24T10:33:03.853 に答える