gpt4 book ai didi

java - 我如何调用一个声明 ArrayList 并从另一个方法引用变量的方法?

转载 作者:行者123 更新时间:2023-12-01 14:21:56 24 4
gpt4 key购买 nike

所以我想做destroyProcesses(processes);当我点击我的 stopButton这是 JButton 。我如何让它在我的代码中工作?

这是我的代码:

        private void Processes() throws IOException, InterruptedException {
// New Thread "processesThread" will start here.
final Object mon = threadBlock;
Thread processesThread = new Thread(new Runnable() {
@Override
public void run() {
synchronized (mon) {
try {
try {
Runtime rt = Runtime.getRuntime();
List<Process> processes = new ArrayList<Process>();
// "runnableTogether" will be the number that the user inputs in the GUI.
switch (runnableTogether) {
case 4:
processes.add(rt.exec("C:/Windows/System32/SoundRecorder.exe"));
case 3:
processes.add(rt.exec("C:/Windows/System32/taskmgr.exe"));
case 2:
processes.add(rt.exec("C:/Windows/System32/notepad.exe"));
case 1:
processes.add(rt.exec("C:/Windows/System32/calc.exe"));
Thread.sleep(5000);
destroyProcesses(processes);
break;
default:
System.exit(0);
break;
}
mon.wait();
} catch (IOException ex) {
}
} catch (InterruptedException ex) {
}
}
}
});
processesThread.start();
// New Thread "processesThread" will end here.
}
private void destroyProcesses(List<Process> processes) {
if (processes == null) {
return;
}
else {
for (Process thisProcess : processes) {
thisProcess.destroy();
}
processes.clear();
}
}
public void actionPerformed(final ActionEvent e) {
if (e.getSource() == stopButton) {
try {
// Destroy processes here.
System.exit(0);
}
catch (Exception ex) {
}
}
}

有什么想法吗?

最佳答案

您需要将进程作为实例变量,如下所示:

public class MyClass {
private List<Process> processes = new ArrayList<Process>();

public MyClass() {
initProcesses();
}

private void initProcesses() {
// init the processes here
}

public void actionPerformed(final ActionEvent e) {
// now here you can use the processes
}
}

希望有帮助!

关于java - 我如何调用一个声明 ArrayList 并从另一个方法引用变量的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17465278/

24 4 0