我希望在请求进行时显示ControlFx MaskerPane。我在按钮操作上有这个代码来发出网络请求。
u32
然而,我的Network类中的验证方法看起来像
if(mp==null){
mp=new MaskerPane();
stackPane.getChildren().add(mp);
mp.setVisible(false);
}
try {
mp.setVisible(true);
JSONObject verifyKey = new Network().verifyKey(pinF.getText(), phoneF.getText(), mp);
if (verifyKey != null) {
String string = verifyKey.getString("ans");
mp.setVisible(false);
if (string.equals("1")) {
// Thanks for buying
} else {
error.setText("Key already used");
error.setVisible(true);
}
}
} catch (JSONException ex) {
mp.setVisible(false);
Logger.getLogger(Buy.class.getName()).log(Level.SEVERE, null, ex);
}
问题是maskerpane在调用网络请求完成之前不会显示。
答案 0 :(得分:0)
我发现我需要在另一个线程中执行网络操作。可以使用Executor服务。这些可以在javafx并发包
中找到if (mp == null) {
mp = new MaskerPane();
stackPane.getChildren().add(mp);
mp.setVisible(false);
}
mp.setVisible(true);
Runnable task = () -> {
try {
JSONObject verifyKey = new Network().verifyKey(pinF.getText(), phoneF.getText(), mp);
if (verifyKey != null) {
String string = verifyKey.getString("ans");
//Updating ui from another thread need you to use Platform.runLatter... So wrapping the below with runLatter to avoid exceptions
mp.setVisible(false);
if (string.equals("1")) {
// Thanks for buying
} else {
error.setText("Key already used");
error.setVisible(true);
}
}
Thread back = new Thread(task);
back.setPriority(Thread.MAX_PRIORITY);
back.setDaemon(true);
back.start();
} catch (JSONException ex) {
mp.setVisible(false);
Logger.getLogger(Buy.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Run the task in a background thread
Thread back = new Thread(task);
back.setPriority(Thread.MAX_PRIORITY);
back.setDaemon(true);
back.start();
https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm