1
我一直在嘗試幾種方法來編寫一個小程序,允許用戶根據他們點擊的按鈕運行三種功能之一。主程序代碼如下所示:如何讓用戶在Java中中斷無限循環?
public class WaspmoteSim extends JFrame implements ActionListener {
public WaspmoteSim() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
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);
setFocusable(true);
}
public static void main(String[] args) {
}
@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);
}
}
//else {ProcessHolder.getInstance().getProcesses().get(YOUR_PROCESS_NAME).destroy();}
}
和第三個按鈕需要調用的函數(我希望能夠中斷一個),如下所示:
public void OperationsMethod() throws IOException, InterruptedException {
Process proc;
while(!IsKeyPressed.isEPressed()) {
String workingDir = System.getProperty("user.dir");
System.out.println(workingDir);
proc = Runtime.getRuntime().exec("cmd.exe /C C:\\Progra~1\\R\\R-3.2.1.\\bin\\Rscript.exe " + workingDir + "\\Fitter.r");
TimeUnit.SECONDS.sleep(4);
}
}
IsKeyPressed的代碼直接來自How do I check if the user is pressing a key?。
但是,當運行第三個功能並按住E鍵時,程序會繼續循環。我究竟做錯了什麼?
你是否獲得無限輸出,或者是整個程序簡單掛? –
'Process#destroy'「might」work,但是,爲了安全起見,您必須運行EDT。 – MadProgrammer
無限輸出;該程序響應良好,但拒絕實際關閉循環。 – Martin