您好,这是我在堆栈上的第一个问题。我遇到了 disablebleProperty()
函数的问题。它使我的 Stage
变成深灰色,看起来很糟糕。当某些 Task
正在运行时,如何禁用对舞台的点击,如以下代码所示:
buttonName.setOnAction((event) -> {
Task task = new Task() {
@Override
protected Integer call() throws Exception {
try {
buttonName.getScene().setCursor(Cursor.WAIT);
buttonName.getScene().getRoot().disableProperty().bind(primaryStage.getScene().cursorProperty().isEqualTo(Cursor.WAIT));
anotherFunction();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
buttonName.getScene().setCursor(Cursor.DEFAULT);
}
return null;
}
};
Thread th = new Thread(task);
th.setDaemon(true);
th.start();
});
最佳答案
您不应从 JavaFX 应用程序线程以外的线程更新 ui。由于 Task.call
在单独的线程上运行,因此您不应在那里运行代码。同时绑定(bind)到 curser 属性而不是同时调用 setDisable(false) 似乎是一个坏主意,特别是因为您从未取消绑定(bind)该属性。
使用 onSucceeded
的事件处理程序来处理任务的成功完成。 (onFailed
和 onCanceled
可用于完成任务的不同方式,但在您发布的代码片段中不会发生这种情况。)
buttonName.setOnAction((event) -> {
buttonName.getScene().setCursor(Cursor.WAIT);
buttonName.setDisable(true);
Task<Void> task = new Task<Void>() {
@Override
protected Void call() throws Exception {
try {
anotherFunction();
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
};
task.setOnSucceeded(evt -> {
buttonName.getScene().setCursor(Cursor.DEFAULT);
buttonName.setDisable(true);
});
Thread th = new Thread(task);
th.setDaemon(true);
th.start();
});
要禁用场景中的其他控件,您可以禁用/重新启用场景的根:
buttonName.getScene().getRoot().setDisable(newValue);
为了防止 JavaFX 在禁用的控件上应用灰色外观(将不透明度设置为 0.4),您可以应用具有更高优先级的不同不透明度,例如通过设置代码的不透明度
buttonName.setOpacity(1);
或者通过使用自定义样式表应用样式
样式.css
*:disabled {
-fx-opacity: 1;
}
场景初始化
scene.getStylesheets().add("style.css");
关于java - 更改disableProperty()函数的颜色/如何禁用舞台上的点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50795288/