Вывод BufferedReader в JTextArea

Я пытаюсь вызвать строку из BufferedReader в другом классе. Я хочу иметь возможность выводить результат в моем JTextArea, который находится в моем основном классе.

Вот мой основной класс:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import java.io.*;
import java.lang.Process.*;

public class FTP {
    public static void main (String []args){
            Runnable runner = new Runnable(){
                public void run()
                {

                    LookAndFeel nimbusLook = new LookAndFeel();
                    nimbusLook.NimbusLookAndFeel();

                    JFrame frame = new JFrame("BNA FTP Diagnose");
                    frame.setVisible(true);
                    frame.setResizable(false);
                    frame.setSize(540, 420);
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setLocation(150, 150);


                    JMenuBar menuBar = new JMenuBar();
                    frame.setJMenuBar(menuBar);

                    JMenu fileMenu = new JMenu("File");
                    menuBar.add(fileMenu);
                    final JMenuItem exitMenuItem = new JMenuItem("Exit");
                    fileMenu.add(exitMenuItem);


                    JMenu helpMenu = new JMenu("Help");
                    menuBar.add(new JPanel());
                    menuBar.add(helpMenu);
                    final JMenuItem aboutMenuItem = new JMenuItem("About");
                    helpMenu.add(aboutMenuItem);



                    JPanel titlePanel = new JPanel(new BorderLayout());
                    frame.add(titlePanel, BorderLayout.NORTH);

                    JLabel titleLabel = new JLabel("FTP Diagnose", JLabel.CENTER);
                    titleLabel.setFont(new Font(null, Font.BOLD, 14));
                    titleLabel.setForeground(Color.BLUE);
                    titlePanel.add(titleLabel);

                    JPanel gridPanel = new JPanel(new GridLayout(1, 1));
                    frame.add(gridPanel);

                    JPanel vendorPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
                    gridPanel.add(vendorPanel);

                    final String vendor [] = {"LLesiant" ,"WK-CCH", "Proquest", "Notes", "Research Institute of America", "Thomson", 
                            "BNAI PDF Processing", " TM Portfolios to Indexing", "Postscript to PRODLOGIN1", "www.firstdoor.net", "psp.bna.com", "WEST", "LexisNexis", "McArdle Printing Company", 
                            "Breaking News Email", "Ex Libris", "Pandora", "Bloomberg Law", "Acquire Media Site 1", "Acquire Media Site 2", "Quicksite", "QA Quicksite"};
                    final JComboBox vendorList = new JComboBox(vendor);
                    vendorPanel.add(vendorList);

                    JPanel diagnoseButtonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
                    gridPanel.add(diagnoseButtonPanel);
                    final JButton diagnoseButton = new JButton("Diagnose");
                    diagnoseButtonPanel.add(diagnoseButton);


                    JPanel centerPanel = new JPanel(new BorderLayout());
                    frame.add(centerPanel, BorderLayout.SOUTH);
                    JPanel commandPanel = new JPanel(new GridLayout(1, 0));
                    centerPanel.add(commandPanel);


                    final JTextArea commandResultArea = new JTextArea(7, 0);
                    JScrollPane scroll = new JScrollPane(commandResultArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
                    commandPanel.add(scroll);
                    commandResultArea.setEditable(false);




                    ActionListener buttonListener = new ActionListener(){

                        public void actionPerformed(ActionEvent ae)

                        {
                            int selectedIndex = vendorList.getSelectedIndex();

                            String llesiant = "ftp.llesiant.com";
                            String wkCCH = "FTP1.cch.com";
                            String proquest = "ftp.proquest.com";
                            String notes = "notes5.bna.com";


                            //String lineThree = null;

                            CommandClass readCommand = new CommandClass();

                            if (selectedIndex == 0)
                            {
                                readCommand.getCommand(llesiant);
                            }
                            else if (selectedIndex == 1)
                            {
                                readCommand.getCommand(wkCCH);
                            }
                            else if (selectedIndex == 2)
                            {
                                readCommand.getCommand(proquest);
                            }
                            else if (selectedIndex == 3)
                            {
                                readCommand.getCommand(notes);
                            }

                        }

                    };
                    diagnoseButton.addActionListener(buttonListener);

                    ActionListener exitListener = new ActionListener (){

                        public void actionPerformed(ActionEvent el)
                        {

                            if (el.getSource()== exitMenuItem)
                            {
                                JOptionPane.showMessageDialog(null, "FTP Program will exit now!");
                                System.exit(0);
                            }

                        }

                    };

                    exitMenuItem.addActionListener(exitListener);

                    ActionListener aboutListener = new ActionListener()
                    {
                        public void actionPerformed(ActionEvent al)
                        {

                            if (al.getSource()== aboutMenuItem)

                            {
                            JOptionPane.showMessageDialog(null, "This Software was made for Editors to. \nDiagnose BNA Bloomberg client FTP site.");

                            }
                        }

                    };
                    aboutMenuItem.addActionListener(aboutListener);             
                    }

            };
            EventQueue.invokeLater(runner);

        }

}

Вот мой CommandClass:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;


public class CommandClass {




    public String line;



    public void getCommand(String ftpSite)

    {


        String command = "ping ";


        try
        {
        Process p = Runtime.getRuntime().exec(command +ftpSite);

        BufferedReader readOutput = new BufferedReader(new InputStreamReader (p.getInputStream()));


        JOptionPane.showMessageDialog(null, "FTP is connected");

        while ((line = readOutput.readLine()) != null)
        {

                System.out.println(line);   

        }
        readOutput.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();

        }

    }





}

Вот мой класс Look and Feel:

import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;

public class LookAndFeel {


    public void NimbusLookAndFeel()
    {

        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception e) {
            // If Nimbus is not available, you can set the GUI to another look and feel.
        }


    }




}

Что я пытаюсь сделать: вывод отлично распечатывается в консоли, но я хочу иметь возможность распечатать его в JTextArea в почтовом классе, также я пытался вернуть значение строковой строки, но, похоже, он продолжает возвращаться с нулевым значением. Если то, что я пытаюсь сделать, невозможно. Есть ли способ получить мой JTextArea.setText для (commandCLass)


person Reazur Rahman    schedule 06.03.2013    source источник
comment
Чтобы быстрее получить помощь, опубликуйте SSCCE.   -  person Andrew Thompson    schedule 07.03.2013


Ответы (2)


FTP-класс:

Я сделал так, что когда вы пингуете сервер, он возвращает строку. Вы можете изменить его, чтобы активно редактировать текст в JTextField, но это работает нормально.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;
import java.io.*;
import java.lang.Process.*;

public class FTP {



  public static void main (String []args)
  {
    Runnable runner = new Runnable(){



      public void run()
      {

        LookAndFeel nimbusLook = new LookAndFeel();
        nimbusLook.NimbusLookAndFeel();

        JFrame frame = new JFrame("BNA FTP Diagnose");
        frame.setVisible(true);
        frame.setResizable(false);
        frame.setSize(540, 420);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocation(150, 150);


        JMenuBar menuBar = new JMenuBar();
        frame.setJMenuBar(menuBar);

        JMenu fileMenu = new JMenu("File");
        menuBar.add(fileMenu);
        final JMenuItem exitMenuItem = new JMenuItem("Exit");
        fileMenu.add(exitMenuItem);


        JMenu helpMenu = new JMenu("Help");
        menuBar.add(new JPanel());
        menuBar.add(helpMenu);
        final JMenuItem aboutMenuItem = new JMenuItem("About");
        helpMenu.add(aboutMenuItem);



        JPanel titlePanel = new JPanel(new BorderLayout());
        frame.add(titlePanel, BorderLayout.NORTH);

        JLabel titleLabel = new JLabel("FTP Diagnose", JLabel.CENTER);
        titleLabel.setFont(new Font(null, Font.BOLD, 14));
        titleLabel.setForeground(Color.BLUE);
        titlePanel.add(titleLabel);

        JPanel gridPanel = new JPanel(new GridLayout(1, 1));
        frame.add(gridPanel);

        JPanel vendorPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        gridPanel.add(vendorPanel);

        final String vendor [] = {"LLesiant" ,"WK-CCH", "Proquest", "Notes", "Research Institute of America", "Thomson", 
          "BNAI PDF Processing", " TM Portfolios to Indexing", "Postscript to PRODLOGIN1", "www.firstdoor.net", "psp.bna.com", "WEST", "LexisNexis", "McArdle Printing Company", 
          "Breaking News Email", "Ex Libris", "Pandora", "Bloomberg Law", "Acquire Media Site 1", "Acquire Media Site 2", "Quicksite", "QA Quicksite"};
        final JComboBox vendorList = new JComboBox(vendor);
        vendorPanel.add(vendorList);

        JPanel diagnoseButtonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        gridPanel.add(diagnoseButtonPanel);
        final JButton diagnoseButton = new JButton("Diagnose");
        diagnoseButtonPanel.add(diagnoseButton);


        JPanel centerPanel = new JPanel(new BorderLayout());
        frame.add(centerPanel, BorderLayout.SOUTH);
        JPanel commandPanel = new JPanel(new GridLayout(1, 0));
        centerPanel.add(commandPanel);


        final JTextArea commandResultArea = new JTextArea(7, 0);
        JScrollPane scroll = new JScrollPane(commandResultArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        commandPanel.add(scroll);
        commandResultArea.setEditable(false);




        ActionListener buttonListener = new ActionListener(){

          public void actionPerformed(ActionEvent ae)

          {
            int selectedIndex = vendorList.getSelectedIndex();

            String llesiant = "ftp.llesiant.com";
            String wkCCH = "FTP1.cch.com";
            String proquest = "ftp.proquest.com";
            String notes = "notes5.bna.com";


            //String lineThree = null;

            CommandClass readCommand = new CommandClass();

            if (selectedIndex == 0)
            {
              commandResultArea.setText(readCommand.getCommand(llesiant)); //these return strings

            }
            else if (selectedIndex == 1)
            {
              commandResultArea.setText(readCommand.getCommand(wkCCH));
            }
            else if (selectedIndex == 2)
            {
              commandResultArea.setText(readCommand.getCommand(proquest));
            }
            else if (selectedIndex == 3)
            {
              commandResultArea.setText(readCommand.getCommand(notes));
            }

          }

        };
        diagnoseButton.addActionListener(buttonListener);

        ActionListener exitListener = new ActionListener (){

          public void actionPerformed(ActionEvent el)
          {

            if (el.getSource()== exitMenuItem)
            {
              JOptionPane.showMessageDialog(null, "FTP Program will exit now!");
              System.exit(0);
            }

          }

        };

        exitMenuItem.addActionListener(exitListener);

        ActionListener aboutListener = new ActionListener()
        {
          public void actionPerformed(ActionEvent al)
          {

            if (al.getSource()== aboutMenuItem)

            {
              JOptionPane.showMessageDialog(null, "This Software was made for Editors to. \nDiagnose BNA Bloomberg client FTP site.");

            }
          }

        };
        aboutMenuItem.addActionListener(aboutListener);             
      }

    };
    EventQueue.invokeLater(runner);

  }

}

Класс команд:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;


public class CommandClass extends FTP {




  public String line, output = "";



  public String getCommand(String ftpSite)

  {


    String command = "ping ";


    try
    {
      Process p = Runtime.getRuntime().exec(command +ftpSite);

      BufferedReader readOutput = new BufferedReader(new InputStreamReader (p.getInputStream()));


      JOptionPane.showMessageDialog(null, "FTP is connected");

      while ((line = readOutput.readLine()) != null)
      {

        System.out.println(line);   
        output += line + "\n";

      }
      readOutput.close();
    }
    catch (IOException e)
    {
      e.printStackTrace();

    }
    return output;
  }





}
person MeryXmas    schedule 06.03.2013
comment
Не могли бы вы объяснить, почему вам нужно было создать класс FTP, расширив его, а также почему вам пришлось объявить класс как строку, которая возвращает значение. и какова цель выходной строки, кажется, что она ничего не устанавливает вверху. Я был бы очень признателен, я пытаюсь научиться этому. - person Reazur Rahman; 07.03.2013

Улучшите свой метод getCommand таким образом, чтобы он возвращал правильное String и использовал это возвращаемое значение в своем основном классе для отображения в JTextArea

public String getCommand(String ftpSite){
    String command = "ping ";
    StringBuffer output = new StringBuffer();
    try{
         Process p = Runtime.getRuntime().exec(command +ftpSite);
         //BufferedReader readOutput = new BufferedReader(new InputStreamReader (p.getInputStream()));
        InputStreamReader ir = new InputStreamReader (p.getInputStream());
        int outputChar = 0;
        while((outputChar = ir.read()) != -1){
            output.append((char)outputChar);
        if(!ir.ready()){ // If the next read is not guarenteed, come out of loop.
            break;
        }
            }
          ir.close();
         JOptionPane.showMessageDialog(null, "FTP is connected");
         //while ((line = readOutput.readLine()) != null){
              //System.out.println(line);   
              //output.append(line).append("\n");
         //}
         //readOutput.close();
    }catch (IOException e){
        e.printStackTrace();
    }
    return output.toString();
}

блок if-else в классе FTP

                CommandClass readCommand = new CommandClass();

                        if (selectedIndex == 0)
                        {
                            commandResultArea.setText(readCommand.getCommand(llesiant));
                        }
                        else if (selectedIndex == 1)
                        {
                            commandResultArea.setText(readCommand.getCommand(wkCCH));
                        }
                        else if (selectedIndex == 2)
                        {
                            commandResultArea.setText(readCommand.getCommand(proquest));
                        }
                        else if (selectedIndex == 3)
                        {
                           commandResultArea.setText(readCommand.getCommand(notes));
                        }
person Ravindra Gullapalli    schedule 06.03.2013
comment
Не могли бы вы объяснить, почему вам нужно было создать класс FTP, расширив его, а также почему вам пришлось объявить класс как строку, которая возвращает значение. и какова цель выходной строки, кажется, что она ничего не устанавливает вверху. Я был бы очень признателен, я пытаюсь научиться этому - person Reazur Rahman; 07.03.2013
comment
Я не унаследовал FTP класс. Я изменил метод getCommand в файле CommandClass. В вашем классе FTP лестница if-else будет изменена, как показано в моем посте. Обновил мой пост. - person Ravindra Gullapalli; 07.03.2013
comment
также у меня есть вопрос, если бы я изменил команду с ping на ftp. Он не выводит никакого сообщения о том, что ftp обычно подключен, когда вы вводите ftp на cmd или unix, и сайт, на котором он говорит, что он подключен, потому что я у меня нет outputStream для моей команды, и если бы я хотел показать сообщение, когда ftp подключен, как мне это сделать или как мне распечатать все, что обычно выводит принтер, когда вы запускаете команду ftp на cmd или unix Спасибо миллион - person Reazur Rahman; 07.03.2013
comment
Я только что попробовал это с помощью команды ftp и не получил никакого ответа, должен ли это быть URL-адрес или что-то вроде ftp.llesiant.com. Я не получил никакого ответа на JTextArea, когда я попытался для одного из FTP-сайт, который я указал в коде - person Reazur Rahman; 07.03.2013
comment
Используя InputStreamReader, я могу добиться этого. Не BufferedReader. Обновление моего ответа. - person Ravindra Gullapalli; 07.03.2013
comment
не могли бы вы дать мне пример, пожалуйста - person Reazur Rahman; 07.03.2013
comment
Я только что попробовал. Приложение просто зависает на некоторое время и ничего не происходит - person Reazur Rahman; 07.03.2013
comment
Я хотел сказать, что когда вы нажимаете кнопку диагностики в графическом интерфейсе, он просто зависает. - person Reazur Rahman; 07.03.2013
comment
Проверьте с помощью WK-CCH. LLesiant выдает тайм-аут запроса через некоторое время. - person Ravindra Gullapalli; 07.03.2013
comment
Кажется, что в верхнем коде у вас есть команда String, установленная для ping, я установил свой на ftp, и он просто зависает, когда я нажимаю кнопку диагностики, и ничего не делает, это приглашение имени пользователя, вы получаете это в консоли или JTextArea - person Reazur Rahman; 07.03.2013
comment
Я пытался распечатать это также на консоли, но это тоже не так. - person Reazur Rahman; 07.03.2013
comment
Я не вижу обновленный код в верхней части Reader ready, это из класса ввода-вывода? - person Reazur Rahman; 07.03.2013
comment
Проверьте условие if внутри цикла while. Reader тоже из пакета java.io. - person Ravindra Gullapalli; 07.03.2013
comment
Также он не возвращает хост, не найденный для заметок, он просто зависает - person Reazur Rahman; 07.03.2013
comment
В командной строке тоже не подключается. Он просто показывает приглашение ftp, но не дает результата какой-либо команды. Я не знаю, как справиться с этой ситуацией. - person Ravindra Gullapalli; 08.03.2013
comment
Да, в командной строке он просто говорит, что хост не найден, но в JtextArea он ничего не говорит - person Reazur Rahman; 08.03.2013