简体   繁体   中英

Java Progress Bar remote execution

I am writing an utility in java that connects to the linux machine and executes a linux command and then displays the results. example of the code is below

try
{
 Sch jsch=new JSch();                   
 host=JOptionPane.showInputDialog("Enter username@hostname",       
 System.getProperty("user.name")+"@localhost"); 
 String user=host.substring(0, host.indexOf('@'));
 host=host.substring(host.indexOf('@')+1);
 session=jsch.getSession(user, host, 22);
 UserInfo ui=new MyUserInfo();
 session.setUserInfo(ui);
 session.connect();
 executor = (ChannelExec) session.openChannel("exec"); 
 executor.setCommand(command1);
 executor.connect();
 BufferedReader reader = new BufferedReader(new InputStreamReader  
 (executor.getInputStream())); 
 String line;
 StringBuilder sb = new StringBuilder();
 while((line= reader.readLine()) != null )
 {
   System.out.println(line);

}

    }

    catch (Exception exp){

    }

I have done everything but somehow it only shows the progress bar updates after the code is getting executed. I have also used swing uitilities but it only executes after the code is run...I need some assistance in putting me in correct path Vilas

JavaFx can be used for progress bar with rich UI. I'll give a sample layout example here with progress bar.

Stage myStage=new Stage(); 
GridPane rootNode = new GridPane();
Scene myScene = new Scene(rootNode, 700, 400);

//add a label username and Text field
rootNode.add(new Label("Username:"), 0, 0);
TextField uname = new TextField();
rootNode.add(uname, 1, 0);

//add a button
Button aButton = new Button("Submit");
rootNode.add(aButton, 1, 4);

myStage.setScene(myScene);
myStage.show();

aButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
        public void handle(ActionEvent e) {
          //Do any simple things
          //Dont do complex things in button handle
          runtask();
        }
});

//runtask method
public void runtask(){
     //label for progress bar
     Label updateLabel = new Label("Processing...");
     ProgressBar progress = new ProgressBar();

     VBox updatePane = new VBox();
     updatePane.getChildren().addAll(updateLabel, progress);

     rootNode.add(updatePane,1,6);

     //create a task
     Task<Void> longTask = new Task<Void>() {
        @Override
        protected Void call() throws Exception {

                //do whatever u want
         }
     };
     longTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent t) {
            //progressbar close when the task completes
            updatePane.setVisible(false);
        }
    });
    progress.progressProperty().bind(longTask.progressProperty());
    updateLabel.textProperty().bind(longTask.messageProperty());

    new Thread(longTask).start();

}

You can use CSS to style and refer https://www.tutorialspoint.com/javafx/javafx_overview.htm for more info. Hope it helps :-)

Please see the code below. I am able to do it using an indeterminate and would like to do it using an progress bar update % wise See the code below

package com.vilas.isstexport;


import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.border.EmptyBorder;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.awt.event.ActionEvent;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.TitledBorder;
import java.awt.Component;

public class Dataexport extends JFrame {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JPanel contentPane;
    private JTextField textField;
    private JButton btnExecute = new JButton("Execute");
    private JProgressBar progressBar = new JProgressBar();
    private JScrollPane scrollPane = new JScrollPane();
    private JTextArea textArea = new JTextArea();
    private BackgroundTask backgroundTask;
    private final JLabel statusLabel = new JLabel("Status: ", JLabel.CENTER);


     private final ActionListener buttonActions = new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                JButton source = (JButton) ae.getSource();
                System.out.println(source.toString());
                if (source == btnExecute) {
                    textArea.setText(null);
                    btnExecute.setEnabled(false);
                    backgroundTask = new BackgroundTask();
                    backgroundTask.execute();
                    progressBar.setIndeterminate(true);
                } 
                /*else if (source == stopButton) {
                    backgroundTask.cancel(true);
                    backgroundTask.done();
                }*/
            }
        };
     private final JLabel lblProgressActivity = new JLabel("Progress Activity");


    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Dataexport frame = new Dataexport();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
        public String getPassword(){ return passwd; }
        public boolean promptYesNo(String str){
          Object[] options={ "yes", "no" };
          int optionOutput=JOptionPane.showOptionDialog(null, 
                 str,
                 "Warning", 
                 JOptionPane.DEFAULT_OPTION, 
                 JOptionPane.WARNING_MESSAGE,
                 null, options, options[0]);
           return optionOutput==0;
        }

        String passwd;
        JTextField passwordField=(JTextField)new JPasswordField(20);

        public String getPassphrase(){ return null; }
        public boolean promptPassphrase(String message){ return true; }
        public boolean promptPassword(String message){
          Object[] ob={passwordField}; 
          int result=
            JOptionPane.showConfirmDialog(null, ob, message,
                                          JOptionPane.OK_CANCEL_OPTION);
          if(result==JOptionPane.OK_OPTION){
            passwd=passwordField.getText();
            return true;
          }
          else{ 
            return false; 
          }
        }
        public void showMessage(String message){
          JOptionPane.showMessageDialog(null, message);
        }
        final GridBagConstraints gbc = 
          new GridBagConstraints(0,0,1,1,1,1,
                                 GridBagConstraints.NORTHWEST,
                                 GridBagConstraints.NONE,
                                 new Insets(0,0,0,0),0,0);
        private Container panel;
        public String[] promptKeyboardInteractive(String destination,
                                                  String name,
                                                  String instruction,
                                                  String[] prompt,
                                                  boolean[] echo){
          panel = new JPanel();
          panel.setLayout(new GridBagLayout());

          gbc.weightx = 1.0;
          gbc.gridwidth = GridBagConstraints.REMAINDER;
          gbc.gridx = 0;
          panel.add(new JLabel(instruction), gbc);
          gbc.gridy++;

          gbc.gridwidth = GridBagConstraints.RELATIVE;

          JTextField[] texts=new JTextField[prompt.length];
          for(int i=0; i<prompt.length; i++){
            gbc.fill = GridBagConstraints.NONE;
            gbc.gridx = 0;
            gbc.weightx = 1;
            panel.add(new JLabel(prompt[i]),gbc);

            gbc.gridx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weighty = 1;
            if(echo[i]){
              texts[i]=new JTextField(20);
            }
            else{
              texts[i]=new JPasswordField(20);
            }
            panel.add(texts[i], gbc);
            gbc.gridy++;
          }

          if(JOptionPane.showConfirmDialog(null, panel, 
                                           destination+": "+name,
                                           JOptionPane.OK_CANCEL_OPTION,
                                           JOptionPane.QUESTION_MESSAGE)
             ==JOptionPane.OK_OPTION){
            String[] response=new String[prompt.length];
            for(int i=0; i<prompt.length; i++){
              response[i]=texts[i].getText();
            }
        return response;
          }
          else{
            return null;  // cancel
          }
        }
      }

    private class BackgroundTask extends SwingWorker<Integer, String> {

        private int status;

        public BackgroundTask() {
            System.out.println("state:: "+(this.getState()).toString());
            statusLabel.setText((this.getState()).toString());
        }

        @Override
        protected Integer doInBackground() {

            //String[] command = { "ls -lrt" };
            //String command = "ls -lrt";
            String command = textField.getText().toString();
            ChannelExec  exec = null;

            try {

                  JSch jsch=new JSch(); 
                  String host=null;


                    host=JOptionPane.showInputDialog("Enter username@hostname",
                                                     System.getProperty("user.name")+
                                                     "@localhost"); 

                  String user=host.substring(0, host.indexOf('@'));
                  host=host.substring(host.indexOf('@')+1);

                  Session session=jsch.getSession(user, host, 22);

               // username and password will be given via UserInfo interface.
                  UserInfo ui=new MyUserInfo();
                  session.setUserInfo(ui);
                  session.connect();
                  exec = (ChannelExec) session.openChannel("exec");
                  exec.setCommand(command);
                  exec.setInputStream(null);
                  exec.setErrStream(System.err);

                  exec.connect();


                String s;
                BufferedReader stdout = new BufferedReader(
                    new InputStreamReader(exec.getInputStream()));

                //System.out.println("s:: "+stdout.readLine());

                while ((s = stdout.readLine()) != null && !isCancelled()) {
                    //System.out.println("s:: "+s);
                    publish(s);
                }
                if (!isCancelled()) {
                    status = exec.getExitStatus();
                }
                exec.getInputStream().close();
                exec.getOutputStream().close();
               // exec.getErrorStream().close();
                //p.destroy();
                exec.disconnect();
                session.disconnect();
            } catch (IOException ex) {
                ex.printStackTrace(System.err);
            } catch (JSchException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return status;
        }

        @Override
        protected void process(java.util.List<String> messages) {

            System.out.println("messages:: "+messages);
            statusLabel.setText((this.getState()).toString());
            for (String message : messages) {
                textArea.append(message + "\n");
            }
        }

        @Override
        protected void done() {
            statusLabel.setText((this.getState()).toString() + " " + status);
            //stopButton.setEnabled(false);
            btnExecute.setEnabled(true);
            progressBar.setIndeterminate(false);
        }

    }




    /**
     * Create the frame.
     */
    public Dataexport() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 761, 497);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);


        JPanel panel = new JPanel();
        panel.setAutoscrolls(true);
        GroupLayout gl_contentPane = new GroupLayout(contentPane);
        gl_contentPane.setHorizontalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_contentPane.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(panel, GroupLayout.DEFAULT_SIZE, 739, Short.MAX_VALUE))
        );
        gl_contentPane.setVerticalGroup(
            gl_contentPane.createParallelGroup(Alignment.LEADING)
                .addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup()
                    .addContainerGap(44, Short.MAX_VALUE)
                    .addComponent(panel, GroupLayout.PREFERRED_SIZE, 431, GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
        );
        panel.setLayout(null);

        textField = new JTextField();
        textField.setBounds(232, 12, 114, 19);
        textField.setColumns(10);
        panel.add(textField);


        btnExecute.setBounds(232, 95, 114, 25);
        panel.add(btnExecute);
        btnExecute.addActionListener(buttonActions);





        progressBar.setEnabled(false);
        progressBar.setBounds(232, 51, 370, 14);
        panel.add(progressBar);
        scrollPane.setAlignmentY(Component.BOTTOM_ALIGNMENT);
        scrollPane.setAlignmentX(Component.RIGHT_ALIGNMENT);
        scrollPane.setViewportBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));

        scrollPane.setBounds(33, 163, 680, 240);
        panel.add(scrollPane);
        scrollPane.setBorder(BorderFactory.createTitledBorder("Output: "));
        scrollPane.setViewportView(textArea);

        JLabel lblEnterTheCommand = new JLabel("Enter the Command");
        lblEnterTheCommand.setBounds(33, 14, 152, 15);
        panel.add(lblEnterTheCommand);
        lblProgressActivity.setBounds(33, 51, 152, 15);

        panel.add(lblProgressActivity);
        contentPane.setLayout(gl_contentPane);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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