我需要为桌面应用程序创建一个弹出窗口。我是通过TCP从客户端到服务器的通信,我希望窗口在等待服务器响应时覆盖主界面。基本上是“请等待回应”的项目。
我已经能够生成一个窗口并在响应具有验证性质时结束,但我无法在舞台上显示任何项目。
Label lblSecondWindow = new Label("This is the second window");
lblSecondWindow.setAlignment(Pos.TOP_LEFT);
lblSecondWindow.autosize();
lblSecondWindow.setVisible(true);
StackPane secondLayout = new StackPane();
secondLayout.getChildren().add(lblSecondWindow);
Scene secondScene = new Scene(secondLayout, 300, 200);
Stage secondStage = new Stage();
secondStage.setTitle("Please Wait");
secondStage.setScene(secondScene);
secondStage.show();
出现一个窗口,但标签无处可寻。如果可能的话,我愿意用另一种方式来解决这个问题,因为我在这个问题上失去的头发比我愿意承认的要多。
答案 0 :(得分:2)
您使用的代码不包含错误。但是,我确定我知道您的错误:您通过在UI线程上进行服务器通信来阻止UI线程。您必须将其移动到另一个线程才能使其正常工作。
我可以使用以下代码重现您的错误:
Label lblSecondWindow = new Label("This is the second window");
lblSecondWindow.setAlignment(Pos.TOP_LEFT);
lblSecondWindow.autosize();
lblSecondWindow.setVisible(true);
StackPane secondLayout = new StackPane();
secondLayout.getChildren().add(lblSecondWindow);
Scene secondScene = new Scene(secondLayout, 300, 200);
Stage secondStage = new Stage();
secondStage.setTitle("Please Wait");
secondStage.setScene(secondScene);
secondStage.show();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
} // Stands for expensive operation (the whole try catch)
secondStage.close();
但不是如果我注释掉try-catch
块,代表您的服务器通信,secondStage.close();
。
可以像这样重写代码以使其工作:
Label lblSecondWindow = new Label("This is the second window");
lblSecondWindow.setAlignment(Pos.TOP_LEFT);
lblSecondWindow.autosize();
lblSecondWindow.setVisible(true);
StackPane secondLayout = new StackPane();
secondLayout.getChildren().add(lblSecondWindow);
Scene secondScene = new Scene(secondLayout, 300, 200);
final Stage secondStage = new Stage();
secondStage.setTitle("Please Wait");
secondStage.setScene(secondScene);
secondStage.show();
new Thread() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
} // Stands for expensive operation (the whole try catch)
Platform.runLater(new Runnable() {
@Override
public void run() {
// UI changes have to be done from the UI thread
secondStage.close();
}
});
}
}.start();