如何在文本区域中显示多行扫描输入 - Java

时间:2016-07-31 09:13:19

标签: java

对,所以我有一个运行bash的算法(用java编写),如果你使用windows,脚本然后将cmd显示在gui的文本区域中,这将显示在下面。它工作正常,因为它成功获取ifconfig信息。但是只显示了一行数据。我的问题是如何获取它以便所有信息都显示在文本区域中。谢谢你提前!

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import java.awt.TextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.Scanner;

public class This_Computer {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void screen1() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    This_Computer window = new This_Computer();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public This_Computer() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 500, 500);
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        final TextArea textArea = new TextArea();
        textArea.setBounds(12, 43, 478, 389);
        frame.getContentPane().add(textArea);

        JButton btnConnectionProperties = new JButton("Connection Properties");
        btnConnectionProperties.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String[] cmdarray = {"ifconfig"};
                try {
                    Process process = Runtime.getRuntime().exec(cmdarray);
                    Scanner scanner1 = new Scanner (process.getInputStream(), "IBM850");
                    scanner1.useDelimiter(" ");
                    String input = scanner1.nextLine ();
                    scanner1.close(); 
                    textArea.setText(input);

                } catch (IOException e1) {
                    System.out.println("ERROR");
                }
            }
        });
        btnConnectionProperties.setBounds(12, 12, 193, 25);
        frame.getContentPane().add(btnConnectionProperties);


    }
}

1 个答案:

答案 0 :(得分:0)

由于我没有足够的时间,我发布了一个快速评论,但我没有提供任何明确的解决方案。所以这是一种解决问题的方法。

而不是:

String input = scanner1.nextline();
//close scanner after reading one line

你可以这样做:

String ins = ""; // the String concatnation way
StringBuilder sb = new StringBuilder(); // The StringBuilder way
String temp;

while(scanner1.hasNextLine())
{
   temp = scanner1.nextLine() + "\n"; // Linebreaker for each line
   ins += temp;
   sb.append(temp);
}

// get String from StringBuilder
// StringBuilder.toString();

注意,同时显示2种方式,你只需要StringBuilder一个String。

我希望这很有用。