当前位置: 首页 > 面试题库 >

输出未重定向到正确的Jtextarea

祁宾白
2023-03-14
问题内容
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

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

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

    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,依此类推。

我不熟悉Java的例子


问题答案:

在JumpHosts中:

TextPanel textPanel = new TextPanel();

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

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

private TextPanel textPanel;
private TextPanel textPanel2;

到您的JumpHosts构造函数中:

JumpHosts(TextPanel textPanel1, TextPanel textPanel2)

要能够引用 相同 TextPanelMainFrame一样。

对后续措施的响应:您需要将TextPanel第一个传递给FormPanel构造函数中的MainFrame构造函数。然后,您将需要修改FormPanel构造函数以将传递TextPanelJumpHosts构造函数。



 类似资料:
  • 我对此很困惑。我把我所有的。JSP文件都放在WEB-INF/页面/里,想访问它们。 我在/forward/*上做了一个requestDispatcher,如下所示 这非常有效,我可以使用/forward/pages/index访问我的JSP文件。不过,我读到的jsp应该是用户无法访问的,但现在它显然是可以访问的。这样做对吗? 另外,现在我们已经重定向到该链接,http://localhost/fo

  • 安全性:编码器:AppBundle\Entity\Usuario:算法:bcrypt#https://symfony.com/doc/current/security.html#b-配置如何加载用户提供程序:db\U提供程序:实体:类:AppBundle:Usuario

  • 我已经创建了一个新的开发人员帐户,并按照快速入门说明进行操作 “快速启动”应用程序正在以下URL上的ds_config中使用预生成的集成密钥运行http://127.0.0.1:5000 创建的应用程序的重定向URI包括http://localhost:5000/ds/callback(这些回调是为Quickstart应用程序自动添加的) 我访问http://127.0.0.1:5000/quic

  • 我试图发出授权请求,但收到错误: 重定向URI未正确注册到DocuSign 这是我正在使用的URL: https://account-d.docusign.com/oauth/auth?response_type=code 这是我注册的重定向URI,与上面的URL匹配: 这是错误: 客户端id与integrator密钥匹配。 有什么指点吗?

  • 问题内容: 我正在尝试使用以下代码重定向在ProcessBuilder的帮助下启动的流程的输出 但是它以失败告终 线程“主”中的异常java.io.IOException:无法运行程序“ / myScript >> / myLogFile 2>&1 <&-&”:java.io.IOException:error = 2,java.lang中没有此类文件或目录.ProcessBuilder.star

  • 问题内容: 我想从Groovy程序中执行foo.bat,并将生成的进程的输出重定向到stdout。Java或Groovy代码示例都可以。 foo.bat可能需要花费几分钟才能运行并生成大量输出,因此我希望在生成后立即查看输出,而不是必须等到该过程完成之后才能立即查看所有输出。 问题答案: 它使用一个类读取执行的程序生成的所有输出,并将其显示在其自己的stdout中。