输出未重定向到正确的Jtextarea [英] Output not getting redirecting to proper Jtextarea

查看:51
本文介绍了输出未重定向到正确的Jtextarea的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MainFrame.java

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;


public class MainFrame extends JFrame{

    private TextPanel textPanel1;
    private TextPanel textPanel2;
    private FormPanel formPanel;
    private JSplitPane splitPane;
    private JTabbedPane tabPane;

    public MainFrame() {

        super("Hello");

        setLayout(new BorderLayout());
        tabPane = new JTabbedPane();        

        textPanel1 = new TextPanel();
        tabPane.addTab("Tab 1", textPanel1);

        textPanel2 = new TextPanel();
        tabPane.addTab("Tab 2", textPanel2);

        //Newly Added code
        formPanel = new FormPanel(textPanel1,textPanel2);

        splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,formPanel,tabPane);

        splitPane.setOneTouchExpandable(true);

        add(splitPane,BorderLayout.CENTER);
//      add(formPanel,BorderLayout.WEST);


        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setMinimumSize(new Dimension(500, 400));
        setSize(600, 500);

    }

}

TextPanel.java

TextPanel.java

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Scrollbar;
import java.io.ByteArrayOutputStream;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;


public class TextPanel extends JPanel {

    private JTextArea textArea1;
    private JTextArea textArea2;
    private FormPanel formPanel;
    //Newly added code 
    private TextPanel textPanel;
    public TextPanel(){

        setLayout(new BorderLayout());

        textArea1 = new JTextArea();
        add(new JScrollPane(textArea1),BorderLayout.CENTER);

        //textArea2 = new JTextArea();
        //add(new JScrollPane(textArea2),BorderLayout.CENTER);


    }
    //Newly added code      
        public void appendText(String string, TextPanel textPanel2) {
    // TODO Auto-generated method stub
    this.textPanel = textPanel2;                                                                                                                                                                                                                                                                                                                                                
    textArea1.append(string);   
}


}

FormPanel.java

FormPanel.java

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.ObjectInputStream.GetField;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.border.Border;


public class FormPanel extends JPanel {

    private static int numberOfTabs = 1;
    private JLabel serverName_1;
    private JLabel serverName_2;
    private JButton startServer_1;
    private JButton startServer_2;
    //Added New Code
    private TextPanel textPanel1;
    private TextPanel textPanel2; 
    JumpHosts jumpHosts = new JumpHosts();

    //Added New Code
    public FormPanel(final TextPanel textPanel1,final TextPanel textPanel2){

        Dimension dim  = getPreferredSize();
        dim.width = 350;
        setPreferredSize(dim);
        setMinimumSize(dim);


        //Added New Code
        this.textPanel = textPanel1;
        this.textPanel = textPanel2;

        serverName_1 = new JLabel("server1 ");
        startServer_1 = new JButton("Start");

        serverName_2 = new JLabel("server2 ");
        startServer_2 = new JButton("Start");


        startServer_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                String[] ev = new String[]{"username@10.10.10.10","username@server1"};
                String cmd = "ls -ltr";
                //jumpHosts.JumpHosts(ev,cmd);
                //Newly added code
                jumpHosts.JumpHosts(ev,cmd,textPanel1);

            }
        });

        startServer_2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                String[] ev = new String[]{"username@10.10.10.10","username@server2"};
                String cmd = "ls -ltr";
                //jumpHosts.JumpHosts(ev,cmd);
                //Newly added code
                jumpHosts.JumpHosts(ev,cmd,textPanel2);

            }
        });

        Border innerborder = BorderFactory.createTitledBorder("Detail");
        Border outerborder = BorderFactory.createEmptyBorder(5, 5, 5, 5);

        setBorder(BorderFactory.createCompoundBorder(outerborder, innerborder));

        layoutComponents();
    }

    public void layoutComponents(){

        setLayout(new GridBagLayout());

        GridBagConstraints gc = new GridBagConstraints();


        //////////// First row ////////////
        gc.gridy = 0;

        gc.weightx = 1;
        gc.weighty = 0.01;

        gc.gridx = 0;
        gc.insets = new Insets(0, 0, 0, 5);
        gc.anchor = GridBagConstraints.FIRST_LINE_START;
        add(serverName_1,gc);

        /////////// Next Column ////////////
        gc.gridy = 0;

        gc.weightx = 2;
        gc.weighty = 0.01;

        gc.gridx = 2;
        gc.insets = new Insets(0, 0, 0, 5);
        gc.anchor = GridBagConstraints.FIRST_LINE_START;
        add(startServer_1,gc);

        //////////// Second row ////////////
        gc.gridy++;

        gc.weightx = 1;
        gc.weighty = 0.1;

        gc.gridx = 0;
        gc.insets = new Insets(0, 0, 0, 5);
        gc.anchor = GridBagConstraints.FIRST_LINE_START;
        add(serverName_2,gc);

        /////////// Next Column ////////////
        //gc.gridy = 1;

        gc.weightx = 2;
        gc.weighty = 0.1;

        gc.gridx = 2;
        gc.insets = new Insets(0, 0, 0, 5);
        gc.anchor = GridBagConstraints.FIRST_LINE_START;
        add(startServer_2,gc);

    }

}

JumpHosts.java

JumpHosts.java

    import com.jcraft.jsch.*;
    import java.awt.*;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;

    import javax.swing.*;

    public class JumpHosts {

        TextPanel textPanel = new TextPanel();

//Newly added code
public void JumpHosts(final String[] arg,final String command,final TextPanel textPanel) {

        StringBuffer resultDisplayBuffer = new StringBuffer();

        SwingWorker sw = new SwingWorker(){

                @Override
                protected Object doInBackground() throws Exception {
                    try{
                          JSch jsch = new JSch();

                          if(arg.length <= 1){
                            System.out.println("This program expects more arguments.");
                            System.exit(-1);
                          }

                          Session session = null;
                          Session[] sessions = new Session[arg.length];

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

                          sessions[0] = session = jsch.getSession(user, host, 22);
                          session.setUserInfo(new MyUserInfo());
                          session.connect();
                          //textPanel.appendText("The session has been established to "+user+"@"+host+"\n");






//Newly added code     
    textPanel.appendText("The session has been established to "+user+"@"+host+"\n",textPanel);


                          for(int i = 1; i < arg.length; i++){
                            host = arg[i];
                            user = host.substring(0, host.indexOf('@'));
                            host = host.substring(host.indexOf('@')+1);

                            int assinged_port = session.setPortForwardingL(0, host, 22);
                            textPanel.appendText("portforwarding: "+
                                            "localhost:"+assinged_port+" -> "+host+":"+22+"\n");
                            sessions[i] = session =
                              jsch.getSession(user, "localhost", assinged_port);

                            session.setUserInfo(new MyUserInfo());
                            session.setHostKeyAlias(host);
                            session.connect();
                            textPanel.appendText("The session has been established to "+
                                            user+"@"+host+"\n");
                          }


                            String sudo_pass;
                            {
                            JTextField passwordField=(JTextField)new JPasswordField(8);
                            Object[] ob={passwordField}; 
                            int result=
                            JOptionPane.showConfirmDialog(null, 
                                 ob,
                                 "Enter password for sudo",
                                 JOptionPane.OK_CANCEL_OPTION);
                            if(result!=JOptionPane.OK_OPTION){
                            System.exit(-1);
                            }  
                            sudo_pass=passwordField.getText();
                            }

                            Channel channel=session.openChannel("exec");

                            // man sudo
                            //   -S  The -S (stdin) option causes sudo to read the password from the
                            //       standard input instead of the terminal device.
                            //   -p  The -p (prompt) option allows you to override the default
                            //       password prompt and use a custom one.
                            ((ChannelExec)channel).setCommand("sudo -S -p '' "+command);

                            InputStream in = channel.getInputStream();
                            OutputStream out = channel.getOutputStream();
                            ((ChannelExec) channel).setErrStream(System.err);

                            channel.connect();
                            out.write((sudo_pass + "\n").getBytes());
                            out.flush();


                            byte[] tmp = new byte[1024];
                            while (true) {
                                while (in.available() > 0) {
                                    int i = in.read(tmp, 0, 1024);
                                    if (i < 0)
                                        break;
                                    textPanel.appendText(new String(tmp,0,i));    
                                }
                                if (channel.isClosed()) {

                                    textPanel.appendText(new String("exit-status: " + channel.getExitStatus())+ "\n");       
                                    break;
                                }
                                try {
                                    Thread.sleep(1000);
                                } catch (Exception ee) {
                                    System.out.println(ee);
                                }
                            }
                            channel.disconnect();
                            textPanel.appendText("Disconnect\n\n");


                         for(int i = sessions.length-1; i >= 0; i--){
                            sessions[i].disconnect();
                          }
                        }


                        catch(Exception e){
                          System.out.println(e);
                        }
                    return null;
                }

                public void done(){
                    try {
                        System.out.println(get());
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
        };
         sw.execute();
    }


      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
          }
        }
      }
    }

因此,每当我单击任何按钮时,输出都将重定向到仅一个文本区域,而其他似乎无法使用.即到最后创建的标签. 我希望当我单击按钮1时,它应该写入选项卡1,而当我单击按钮2时,它应该写入选项卡2,依此类推.

so whenever I am clicking on any button the output gets redirected to only one textarea whereas other seems to be no usable. i.e to the last created tab. I want that when I am clicking on button 1 then it should write to tab 1 and when I am clicking on button 2 then it should write to tab 2 and so on.

由于我是Java新手而欣赏的示例

Examples appreciated as I am new to java

推荐答案

在JumpHosts中:

In JumpHosts:

TextPanel textPanel = new TextPanel();

您创建一个TextPanel的实例,该实例在程序中没有其他对象引用.这不是您在MainFrame中创建的TextPanel之一.

you create an instance of TextPanel which is referenced by no other object in the program. This is not either of the TextPanels you created in MainFrame.

您需要传递在MainFrame中创建的TextPanel,即:

You need to pass the TextPanels created in MainFrame, namely:

private TextPanel textPanel;
private TextPanel textPanel2;

进入您的JumpHosts构造函数:

JumpHosts(TextPanel textPanel1, TextPanel textPanel2)

能够引用与MainFrame相同的 TextPanel.

对后续措施的回应: 您需要先从MainFrame构造函数中将TextPanel传递给FormPanel构造函数.然后,您需要修改您的FormPanel构造函数,以将TextPanel传递给您的JumpHosts构造函数.

Response to Followup: You will need to pass your TextPanel first to your FormPanel constructor from within your MainFrame constructor. You will then need to modify your FormPanel contructor to pass the TextPanel to your JumpHosts constructor.

这篇关于输出未重定向到正确的Jtextarea的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆