2016-07-31 54 views
0

正確,所以我有一個運行bash或cmd的算法(用java編寫),如果使用Windows,腳本,然後將其顯示在文本區域中將在下面顯示的gui中。它工作正常,因爲它成功獲取了ifconfig信息。但是隻顯示一行數據。我的問題是如何獲取它,以便所有信息都顯示在文本區域中。先謝謝你!如何在文本區域顯示多行掃描儀輸入 - Java

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); 


    } 
} 
+0

從我所看到的,你只能調用scanner.nextline()一次和那裏只讀一行。您應該繼續構建字符串,直到沒有剩餘行。 (可以連接一個String對象或使用StringBuilder,但不要忘記在每行之後添加一個換行符!) – n247s

+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(); 

注意,這兩種方式都在同一時間顯示,你只需要StringBuilder的A弦。

我希望這是有用的。