I know this is a race condition, and I've tried a few methods to solve it, including an unsuccessful use of invokeAndWait to no avail. All I want to do is have it change the text on the button to "Connecting", however before the UI updates, it starts the ts = new TallyState(); call which freezes the program for up to 20 seconds while it tries to reach the controller.
JButton btnConnectSerial = new JButton("Connect Controller");
btnConnectSerial.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnConnectSerial.setText("Connecting");
try {
ts = new TallyState();
} catch (IOException tse) {
JOptionPane.showMessageDialog(null, "Failed to Connect to Controller");
return;
} catch (Exception tse2) {
}
I'm sure this has been answered before but I can't seem to phrase my question correctly to Google to get the answer I need.
Also tried this but the rest of the ActionListener executes. It needs wait to know if "ts" was able to be built (e.g. the connection doesn't time out and thus throw exception/message).
JButton btnConnectSerial = new JButton("Connect Controller");
btnConnectSerial.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnConnectSerial.setText("Connecting");
SwingWorker myWorker= new SwingWorker<String, Void>() {
@Override
protected String doInBackground() throws Exception {
try {
ts = new TallyState();
} catch (IOException tse) {
JOptionPane.showMessageDialog(null, "Failed to Connect to Controller");
return null;
} catch (Exception tse2) {
}
return null;
}
};
myWorker.execute();
Referenced: Swing, how to properly update the UI, invokeAndWait method in SwingUtilities and links off of them.