[英]How do I let a user interrupt an endless loop in 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的代碼直接來自如何檢查用戶是否按了鍵? 。
但是,當運行第三個功能並按住E鍵時,程序將繼續循環。 我究竟做錯了什么?
您正在Swing事件分配線程中開始一個無限循環。 這意味着您的actionPerformed
方法永無止境。 這意味着Swing被阻止,無法處理任何新的按鈕單擊或任何其他類型的事件。
使用SwingWorker啟動您的OperationsMethod()
。 並使用共享和同步變量在Swing類和SwingWorker之間共享按鈕狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.