私の質問は、TextFieldだけでなく、この特定のタイプのノードのみを含む広い範囲のノードに適用されます。TextFieldバインディングを適切に処理し、ノード参照をタスクと分離して保持する方法
私のアプリケーションはChoiceBoxから作られた都市の選択に基づいて国の名前が表示されますテキストフィールドの内容を変更します。
私はcountryTextField
のテキストを設定することでこれを実現それはうまく動作しますが、実際に私がやりたいことは完全に分離され
@FXML
public void handleCityChoice() {
new Thread(new CityChoiceTask(cityChoiceBox.getValue())).start();
}
class CityChoiceTask extends Task<Void> {
String selection;
CityChoiceTask(String selection) {
this.selection = selection;
}
@Override
public Void call() {
Platform.runLater(() -> countryTextField.setText(Datasource.getInstance().
getCountryNameByCityName(selection)));
return null;
}
}
:選択ボックスのonAction
イベントハンドラを使用してTask<Void>
ノードはTask
コードを参照しているので、そうするのがベストプラクティスです(私はちょうど学生ですから、これについて間違っていれば正解ですが、私が教えたものです)。私は、バインドが実行される前にタスクスレッドが完了していないので、それがあると信じて、以下を試してみましたが、NullPointerException
を投げ続ける:
@FXML
public void handleCityChoice() {
Task task = new CityChoiceTask(cityChoiceBox.getValue());
new Thread(task).start();
countryTextField.textProperty().bind(task.valueProperty());
}
class CityChoiceTask extends Task<SimpleStringProperty> {
String selection;
CityChoiceTask(String selection) {
this.selection = selection;
}
@Override
public SimpleStringProperty call() {
String result = Datasource.getInstance().getCountryNameByCityName(selection));
return new SimpleStringProperty(result);
}
}
また、System.out.println(task.valueProperty());
プリント:
をOBJECTPROPERTY [豆:[email protected]、 名前:値、値:NULL]
スレッドが実際に実行されていない理由は、NullPointerException
を投げているのですが、それを修正する方法はありますか?
TableViewを使用すると、この種のバインドがうまく動作します。 例えば、FXCollections.observableArrayList
のValuePropertyを返すTaskを使用すると、スレッドが実行を終了したときに関係なく、myTableView.itemsProperty().bind(task);
のようなものが正常に機能します。
2番目のコードスニペットで 'Task'にtypeパラメータを追加してみてください... – fabian