目前我尝试使用 GUI 来制作应用程序。该应用程序必须使用一些命令运行 cmd。我正在努力去做。我想实现行动(当我按下“搜索”按钮时命令提示符打开)。我尝试使用 ProcessBuilder 来实现目标,但没有结果。正如您在下面看到的,我尝试使用“dir”命令运行 cmd。我尝试在不运行某些命令的情况下执行操作,但 CMD 正在窃取而不运行。因此,我们在任务管理器中看不到窗口和进程。 这是我的代码:
package sys.tool;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//Создаем поля
public class MainWindow extends JFrame{
private JLabel lcn = new JLabel("Enter computer name:");
private JTextField icn = new JTextField("", 5);
private JButton search = new JButton("Search");
private JLabel lun = new JLabel("Enter user name:");
private JTextField iun = new JTextField("", 5);
private JLabel empty = new JLabel("");
public MainWindow (){
super("SysAdminTool");
this.setBounds(100, 100, 700 , 90);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
Container container = this.getContentPane();
container.setLayout(new GridLayout(3, 2 , 1, 1));
container.add(lcn);
container.add(icn);
container.add(lun);
container.add(iun);
container.add(empty);
search.addActionListener(new SearchEventListener());
container.add(search); //this is button
}
class SearchEventListener implements ActionListener{
public void actionPerformed (ActionEvent e){
ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "dir C:\\Users"); \\here I try to run cmd with command "dir"
}
}
}
最佳答案
在操作系统上运行命令。
String command = "command of the operating system";
Process process = Runtime.getRuntime().exec(command);
关于java - 如何从 java 应用程序运行 Windows 命令提示符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59090173/