I'm writing a small program that runs one of three samples of code depending on which button is pressed. With the third button, a sample of code should run until the JFrame is closed, or until a button is pressed (I don't really mind how it's stopped, just as long as the user has a method of stopping the loop). The code is run, and a delay of 8 seconds is added to ensure the code finished running before it loops.
How do I implement this? The program doesn't seem to terminate when looping, even when I try to close it by clicking the close button in the JFrame.
The main part of the program looks as follows:
public class WaspmoteSim extends JFrame implements ActionListener {
public WaspmoteSim() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
//getContentPane().setLayout(new GridLayout(1, 3, 10, 10));
getContentPane().setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(30,30,30,30);
c.ipadx = 10;
c.ipady = 30;
setSize(700, 150);
setLocation(100, 100);
JButton button1 = new JButton("Demonstration Mode");
button1.addActionListener(this);
add(button1, c);
JButton button2 = new JButton("Distribution Fitting Mode");
button2.addActionListener(this);
add(button2, c);
JButton button3 = new JButton("Operational Mode");
button3.addActionListener(this);
add(button3, c);
setVisible(true);
}
public static void main(String[] args) {
new WaspmoteSim();
}
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("Demonstration Mode")) {
try {
DemoMethod();
} catch (IOException ex) {
Logger.getLogger(WaspmoteSim.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (command.equals("Distribution Fitting Mode")) {
try {
FittingMethod();
} catch (IOException ex) {
Logger.getLogger(WaspmoteSim.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (command.equals("Operational Mode")) {
try {
OperationsMethod();
} catch (IOException ex) {
Logger.getLogger(WaspmoteSim.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(WaspmoteSim.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
The code that I want to run on a loop looks like this:
public void OperationsMethod() throws IOException, InterruptedException {
while(true) {
String workingDir = System.getProperty("user.dir");
System.out.println(workingDir);
Process proc;
proc = Runtime.getRuntime().exec("cmd.exe /C C:\\Progra~1\\R\\R-3.2.1.\\bin\\Rscript.exe " + workingDir + "\\Fitter.r");
TimeUnit.SECONDS.sleep(8);
}
}