Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7847459
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T17:54:14+00:00 2026-06-02T17:54:14+00:00

I have two classes. one to run the program and the other for being

  • 0

I have two classes. one to run the program and the other for being the GUI. built the first using a simple out.print but I then realised I needed the output to be in a JTextArea rather then the console. so I put together a gui for it but idk whether to put the gui in my running class or to call my gui from the running class.
Here’s the running code

import com.jcraft.jsch.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.JTextArea;
import java.util.Vector;

public class Sftp{
static JTextArea guiConsole = new JTextArea(10,10);
  public static void main(String[] arg){

    try{
      JSch jsch=new JSch();

      String host=null;
      if(arg.length>0){
        host=arg[0];
      }
      else{
        host=JOptionPane.showInputDialog("Enter username@hostname",
                                         System.getProperty("user.name")+
                                         "@localhost"); 
      }
      String user=host.substring(0, host.indexOf('@'));
      host=host.substring(host.indexOf('@')+1);
      int port=22;

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

      // username and password will be given via UserInfo interface.
      UserInfo ui=new MyUserInfo();
      session.setUserInfo(ui);

      session.connect();

      Channel channel=session.openChannel("sftp");
      channel.connect();
      ChannelSftp c=(ChannelSftp)channel;

      java.io.InputStream in=System.in;


      java.util.Vector<String> cmds=new java.util.Vector<String>();
      byte[] buf=new byte[1024];
      int i;
      String str;
      int level=0;

      while(true){
    guiConsole.append("sftp> ");
    cmds.removeAllElements();
        i=in.read(buf, 0, 1024);
    if(i<=0)break;

        i--;
        if(i>0 && buf[i-1]==0x0d)i--;
        //str=new String(buf, 0, i);
        //guiConsole.append("|"+str+"|");
    int s=0;
    for(int ii=0; ii<i; ii++){
          if(buf[ii]==' '){
            if(ii-s>0){ cmds.addElement(new String(buf, s, ii-s)); }
        while(ii<i){if(buf[ii]!=' ')break; ii++;}
        s=ii;
      }
    }
    if(s<i){ cmds.addElement(new String(buf, s, i-s)); }
    if(cmds.size()==0)continue;

    String cmd=cmds.elementAt(0);
    if(cmd.equals("quit")){
          c.quit();
      break;
    }
    if(cmd.equals("exit")){
          c.exit();
      break;
    }
    if(cmd.equals("rekey")){
      session.rekey();
      continue;
    }
    if(cmd.equals("compression")){
          if(cmds.size()<2){
        guiConsole.append("compression level: "+level);
            continue;
      }
      try{
        level=Integer.parseInt(cmds.elementAt(1));
        if(level==0){
          session.setConfig("compression.s2c", "none");
          session.setConfig("compression.c2s", "none");
        }
        else{
              session.setConfig("compression.s2c", "zlib@openssh.com,zlib,none");
              session.setConfig("compression.c2s", "zlib@openssh.com,zlib,none");
        }
      }
      catch(Exception e){}
          session.rekey();
      continue;
    }
    if(cmd.equals("cd") || cmd.equals("lcd")){
          if(cmds.size()<2) continue;
      String path=cmds.elementAt(1);
      try{
        if(cmd.equals("cd")) c.cd(path);
        else c.lcd(path);
      }
      catch(SftpException e){
        guiConsole.append(e.toString());
      }
      continue;
    }
    if(cmd.equals("rm") || cmd.equals("rmdir") || cmd.equals("mkdir")){
          if(cmds.size()<2) continue;
      String path=cmds.elementAt(1);
      try{
        if(cmd.equals("rm")) c.rm(path);
        else if(cmd.equals("rmdir")) c.rmdir(path);
        else c.mkdir(path);
      }
      catch(SftpException e){
        guiConsole.append(e.toString());
      }
      continue;
    }
    if(cmd.equals("chgrp") || cmd.equals("chown") || cmd.equals("chmod")){
          if(cmds.size()!=3) continue;
      String path=cmds.elementAt(2);
      int foo=0;
      if(cmd.equals("chmod")){
            byte[] bar=cmds.elementAt(1).getBytes();
            int k;
            for(int j=0; j<bar.length; j++){
              k=bar[j];
          if(k<'0'||k>'7'){foo=-1; break;}
          foo<<=3;
          foo|=(k-'0');
        }
        if(foo==-1)continue;
      }
      else{
        try{foo=Integer.parseInt(cmds.elementAt(1));}
        catch(Exception e){continue;}
      }
      try{
        if(cmd.equals("chgrp")){ c.chgrp(foo, path); }
        else if(cmd.equals("chown")){ c.chown(foo, path); }
        else if(cmd.equals("chmod")){ c.chmod(foo, path); }
      }
      catch(SftpException e){
        guiConsole.append(e.toString());
      }
      continue;
    }
    if(cmd.equals("pwd") || cmd.equals("lpwd")){
           str=(cmd.equals("pwd")?"Remote":"Local");
       str+=" working directory: ";
          if(cmd.equals("pwd")) str+=c.pwd();
      else str+=c.lpwd();
      guiConsole.append(str);
      continue;
    }
    if(cmd.equals("ls") || cmd.equals("dir")){
      String path=".";
      if(cmds.size()==2) path=cmds.elementAt(1);
      try{
       Vector vv=c.ls(path);
        if(vv!=null){
          for(int ii=0; ii<vv.size(); ii++){
          //    guiConsole.appendln(vv.elementAt(ii).toString());

                Object obj=vv.elementAt(ii);
                if(obj instanceof com.jcraft.jsch.ChannelSftp.LsEntry){
                   guiConsole.append(((com.jcraft.jsch.ChannelSftp.LsEntry)obj).getLongname());
                }

          }
        }
      }
      catch(SftpException e){
        guiConsole.append(e.toString());
      }
      continue;
    }
    if(cmd.equals("lls") || cmd.equals("ldir")){
      String path=".";
      if(cmds.size()==2) path=cmds.elementAt(1);
      try{
        java.io.File file=new java.io.File(path);
        if(!file.exists()){
          guiConsole.append(path+": No such file or directory");
              continue; 
            }
        if(file.isDirectory()){
          String[] list=file.list();
          for(int ii=0; ii<list.length; ii++){
        guiConsole.append(list[ii]);
          }
          continue;
        }
        guiConsole.append(path);
      }
      catch(Exception e){
        guiConsole.append(e.toString());
      }
      continue;
    }
    if(cmd.equals("get") || 
       cmd.equals("get-resume") || cmd.equals("get-append") || 
       cmd.equals("put") || 
       cmd.equals("put-resume") || cmd.equals("put-append")
       ){
      if(cmds.size()!=2 && cmds.size()!=3) continue;
      String p1=cmds.elementAt(1);
          //  String p2=p1;
      String p2=".";
      if(cmds.size()==3)p2=cmds.elementAt(2);
      try{
        SftpProgressMonitor monitor=new MyProgressMonitor();
        if(cmd.startsWith("get")){
          int mode=ChannelSftp.OVERWRITE;
          if(cmd.equals("get-resume")){ mode=ChannelSftp.RESUME; }
          else if(cmd.equals("get-append")){ mode=ChannelSftp.APPEND; } 
          c.get(p1, p2, monitor, mode);
        }
        else{ 
          int mode=ChannelSftp.OVERWRITE;
          if(cmd.equals("put-resume")){ mode=ChannelSftp.RESUME; }
          else if(cmd.equals("put-append")){ mode=ChannelSftp.APPEND; } 
          c.put(p1, p2, monitor, mode); 
        }
      }
      catch(SftpException e){
        guiConsole.append(e.toString());
      }
      continue;
    }
    if(cmd.equals("ln") || cmd.equals("symlink") || cmd.equals("rename")){
          if(cmds.size()!=3) continue;
      String p1=cmds.elementAt(1);
      String p2=cmds.elementAt(2);
      try{
        if(cmd.equals("rename")) c.rename(p1, p2);
        else c.symlink(p1, p2);
      }
      catch(SftpException e){
        guiConsole.append(e.toString());
      }
      continue;
    }
    if(cmd.equals("stat") || cmd.equals("lstat")){
          if(cmds.size()!=2) continue;
      String p1=cmds.elementAt(1);
      SftpATTRS attrs=null;
      try{
        if(cmd.equals("stat")) attrs=c.stat(p1);
        else attrs=c.lstat(p1);
      }
      catch(SftpException e){
        guiConsole.append(e.toString());
      }
      if(attrs!=null){
            guiConsole.append(attrs.toString());
      }
      else{
      }
      continue;
    }
    if(cmd.equals("readlink")){
          if(cmds.size()!=2) continue;
      String p1=cmds.elementAt(1);
      String filename=null;
      try{
        filename=c.readlink(p1);
            guiConsole.append(filename);
      }
      catch(SftpException e){
        guiConsole.append(e.toString());
      }
      continue;
    }
    if(cmd.equals("realpath")){
          if(cmds.size()!=2) continue;
      String p1=cmds.elementAt(1);
      String filename=null;
      try{
        filename=c.realpath(p1);
            guiConsole.append(filename);
      }
      catch(SftpException e){
          guiConsole.append(e.toString());
      }
      continue;
    }
    if(cmd.equals("version")){
      guiConsole.append("SFTP protocol version "+c.version());
      continue;
    }
    if(cmd.equals("help") || cmd.equals("?")){
      guiConsole.append(help);
      continue;
    }
        guiConsole.append("unimplemented command: "+cmd);
      }
      session.disconnect();
    }
    catch(Exception e){
      guiConsole.append(e.toString());
    }
    System.exit(0);
  }

  public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
    public String getPassword(){ return passwd; }
    public boolean promptYesNo(String str){
      Object[] options={ "yes", "no" };
      int foo=JOptionPane.showOptionDialog(null, 
             str,
             "Warning", 
             JOptionPane.DEFAULT_OPTION, 
             JOptionPane.WARNING_MESSAGE,
             null, options, options[0]);
       return foo==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
      }
    }
  }

/*
  public static class MyProgressMonitor implements com.jcraft.jsch.ProgressMonitor{
    JProgressBar progressBar;
    JFrame frame;
    long count=0;
    long max=0;

    public void init(String info, long max){
      this.max=max;
      if(frame==null){
        frame=new JFrame();
    frame.setSize(200, 20);
        progressBar = new JProgressBar();
      }
      count=0;

      frame.setTitle(info);
      progressBar.setMaximum((int)max);
      progressBar.setMinimum((int)0);
      progressBar.setValue((int)count);
      progressBar.setStringPainted(true);

      JPanel p=new JPanel();
      p.add(progressBar);
      frame.getContentPane().add(progressBar);
      frame.setVisible(true);
      System.guiConsole.appendln("!info:"+info+", max="+max+" "+progressBar);
    }
    public void count(long count){
      this.count+=count;
      System.guiConsole.appendln("count: "+count);
      progressBar.setValue((int)this.count);
    }
    public void end(){
      System.guiConsole.appendln("end");
      progressBar.setValue((int)this.max);
      frame.setVisible(false);
    }
  }
*/

  public static class MyProgressMonitor implements SftpProgressMonitor{
    ProgressMonitor monitor;
    long count=0;
    long max=0;
    public void init(int op, String src, String dest, long max){
      this.max=max;
      monitor=new ProgressMonitor(null, 
                                  ((op==SftpProgressMonitor.PUT)? 
                                   "put" : "get")+": "+src, 
                                  "",  0, (int)max);
      count=0;
      percent=-1;
      monitor.setProgress((int)this.count);
      monitor.setMillisToDecideToPopup(1000);
    }
    private long percent=-1;
    public boolean count(long count){
      this.count+=count;

      if(percent>=this.count*100/max){ return true; }
      percent=this.count*100/max;

      monitor.setNote("Completed "+this.count+"("+percent+"%) out of "+max+".");     
      monitor.setProgress((int)this.count);

      return !(monitor.isCanceled());
    }
    public void end(){
      monitor.close();
    }
  }

  private static String help =
"      Available commands:\n"+
"      * means unimplemented command.\n"+
"cd path                       Change remote directory to 'path'\n"+
"lcd path                      Change local directory to 'path'\n"+
"chgrp grp path                Change group of file 'path' to 'grp'\n"+
"chmod mode path               Change permissions of file 'path' to 'mode'\n"+
"chown own path                Change owner of file 'path' to 'own'\n"+
"help                          Display this help text\n"+
"get remote-path [local-path]  Download file\n"+
"get-resume remote-path [local-path]  Resume to download file.\n"+
"get-append remote-path [local-path]  Append remote file to local file\n"+
"*lls [ls-options [path]]      Display local directory listing\n"+
"ln oldpath newpath            Symlink remote file\n"+
"*lmkdir path                  Create local directory\n"+
"lpwd                          Print local working directory\n"+
"ls [path]                     Display remote directory listing\n"+
"*lumask umask                 Set local umask to 'umask'\n"+
"mkdir path                    Create remote directory\n"+
"put local-path [remote-path]  Upload file\n"+
"put-resume local-path [remote-path]  Resume to upload file\n"+
"put-append local-path [remote-path]  Append local file to remote file.\n"+
"pwd                           Display remote working directory\n"+
"stat path                     Display info about path\n"+
"exit                          Quit sftp\n"+
"quit                          Quit sftp\n"+
"rename oldpath newpath        Rename remote file\n"+
"rmdir path                    Remove remote directory\n"+
"rm path                       Delete remote file\n"+
"symlink oldpath newpath       Symlink remote file\n"+
"readlink path                 Check the target of a symbolic link\n"+
"realpath path                 Canonicalize the path\n"+
"rekey                         Key re-exchanging\n"+
"compression level             Packet compression will be enabled\n"+
"version                       Show SFTP version\n"+
"?                             Synonym for help";
}

And here’s the gui.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CommandBox extends JPanel implements ActionListener {
protected JTextField textField;
protected JTextArea textArea;
private final static String newline = "\n";

public CommandBox() {
    super(new GridBagLayout());

    textField = new JTextField(20);
    textField.addActionListener(this);

    textArea = new JTextArea(5, 20);
    textArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(textArea);

    //Add Components to this panel.
    GridBagConstraints c = new GridBagConstraints();
    c.gridwidth = GridBagConstraints.REMAINDER;

    c.fill = GridBagConstraints.HORIZONTAL;
    add(textField, c);

    c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    c.weighty = 1.0;
    add(scrollPane, c);
}

public void actionPerformed(ActionEvent evt) {
    String text = textField.getText();
    textArea.append(text + newline);
    textField.selectAll();

    //Make sure the new text is visible, even if there
    //was a selection in the text area.
    textArea.setCaretPosition(textArea.getDocument().getLength());
}

private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("VSI");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Add contents to the window.
    frame.add(new CommandBox());

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    //Schedule a job for the event dispatch thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}
}

My Question being what would you do. You being programmers much more skilled and knowledgeable then I.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T17:54:15+00:00Added an answer on June 2, 2026 at 5:54 pm

    If you create a getter for the JTextArea in GUI class, you can set the text to the JTextArea by creating an object in the class you want to output the text. See the example below:

    CommandBox commandBox = new CommandBox();
    commandBox.getTextArea().setText("Your text");
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have two classes. One creates the GUI in JApplet , and the other
Is it possible to have two step definition classes with first being in one
I have two basic questions. The first one is about function in other classes.
I have two classes one of which inherits from the other. Im trying to
First I want to describe my situation briefly. I have two classes, one MainClass
I have the following two classes, one inherits from the other Class A{ void
I have a class that contains objects of two other classes. I need one
I have written two simple Java classes (one of them containing main(), and the
I have two classes one and two . Both run threads. class Two is
I have two classes with one extending the other. They both have a method

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.