2017-10-20 89 views
1

我有一個帶有一些文本的JLabel,我想通過JLabel運行「echo%USERNAME%」命令,以便一旦我運行代碼的NetBeans IDE 8.2它應該打印到以下Windows 7最終用戶Java - 我如何通過JLabel運行特定的DOS命令

。例如JLabel的文本的用戶名:我的JLabel與文字:「你好觀衆」 我想觀衆改變與用戶名回聲%USERNAME%的幫助,以便它應該打印在Windows 7最終用戶的用戶名上的JLabel

謝謝

回答

2

鴨用於回答問題有關的問題,但您希望獲取帳戶的用戶名並將其存儲在字符串中,然後將其用作某個對象的屬性?

如果是這樣,有一個叫System.getProperty("user.name");

法這是就我的理解你的問題是,道歉,如果這是不正確。另外,對於運行shell命令(特定於平臺),我將使用ProcessBuilder或Runtime.exec("%USERNAME");,具體取決於您使用的Java版本。隨着兩人的後面,this也會有幫助

+0

感謝您的答覆,但有什麼辦法運行System.getProperty(「user.name」);在NetBeans上編寫代碼後在JLabel上編寫代碼 –

+0

編譯代碼與編譯代碼不一樣。如果你想運行你的代碼,編譯是不夠的,你必須讓JVM執行你的代碼。 – Brenann

+1

@ Brenann Oct謝謝兄弟,我終於在Java的jLabel的幫助下運行了它,即jLabel.setText(「Welcome」+ System.getProperty(「user.name」)); –

1

如果你想要的是計算機的用戶名然後使用System.getProperty("user.name");是要走的路一切手段。但是,如果有其他項目想要在整個Windows命令扔提示,那麼你可能想利用這樣的一個RUNCMD()方法:

List<String> list = runCMD("/C echo %USERNAME%"); 
if (!list.isEmpty()) { 
    for (int i = 0; i < list.size(); i++) { 
     System.out.println(list.get(i)); 
    } 
} 

控制檯將顯示當前用戶名。

的方法可能是這個樣子:

public List<String> runCMD(String commandString) { 
    // Remove CMD from the supplied Command String 
    // if it exists. 
    if (commandString.toLowerCase().startsWith("cmd ")) { 
     commandString = commandString.substring(4); 
    } 

    List<String> result = new ArrayList<>(); 
    try { 
     // Fire up the Command Prompt and process the 
     // supplied Command String. 
     Process p = Runtime.getRuntime().exec("cmd " + commandString); 
     // Read the process input stream of the command prompt. 
     try (BufferedReader in = new BufferedReader(
       new InputStreamReader(p.getInputStream()))) { 
      String line = null; 
      // Store what is in the stream into our ArrayList. 
      while ((line = in.readLine()) != null) { 
       result.add(line); 
      } 
     } 
     p.destroy(); // Kill the process 
     return result; 
    } 
    catch (IOException e) { 
     System.err.println("runCMD() Method Error! - IO Error during processing " 
         + "of the supplied command string!\n" + e.getMessage()); 
     return null; 
    } 
}