我一直在尝试几种方法来编写一个小程序,允许用户根据他们点击的按钮运行三种功能中的一种。主程序的代码如下:
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键时,程序只是继续循环。我做错了什么?
答案 0 :(得分:1)
您正在Swing事件调度线程中启动无限循环。这意味着您的actionPerformed
方法永远不会结束。这意味着Swing被阻止,无法处理任何新的按钮点击或任何其他类型的事件。
使用SwingWorker启动OperationsMethod()
。并使用共享和同步变量来共享Swing类和SwingWorker之间的按钮状态。