2017-10-20 93 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; 
    } 
}