So I want to do destroyProcesses(processes);
when I click my stopButton
which is a JButton
. How would I get this to work in my code?
Here is my code:
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) {
}
}
}
Any ideas?
You need to put the processes as a instance variable, like the following:
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
}
}
Hope that helps!