如何从不同的舞台(窗口)向已存在的ListView添加项目。
基本上我只想将WindowView中的Text从Window 2添加到ListView中的ListView。
提前致谢。
抱歉,我忘了这是我在控制器课程中到目前为止所做的:(我是javafx的初学者......)
(下面我尝试将一个字符串添加到ListView但这不起作用......我不知道为什么)
public class ClientGUIController implements Initializable {
@FXML private Text usernameText;
@FXML private Button cancelButtonNewDate;
@FXML private TextField newDateTitel,newDateJahr;
@FXML private TextArea newDateNotiz;
@FXML private ComboBox<String> newDateTag,newDateMonat,newDateStunde,newDateMinute;
@FXML private ListView<String> terminListView;
private ObservableList<String> termine =
FXCollections.observableArrayList();
private ObservableList<String> listItems = FXCollections.observableArrayList("Add Items here");
@Override
public void initialize(URL location, ResourceBundle resources) {
}
public Text getUsernameText() {
return usernameText;
}
public void setUsernameText(String username ) {
this.usernameText.setText(username);
terminListView.setItems(listItems);
listItems.add("test");
}
public void newDate() {
Stage newDate = new Stage();
Parent root;
try {
root = FXMLLoader.load(getClass().getResource("newDate.fxml"));
// FXMLLoader loader = new FXMLLoader();
// root = (Parent) loader.load(getClass().getResource("NewDate.fxml").openStream());
} catch (IOException e) {
e.printStackTrace();
return;
}
Scene sceneNewDate = new Scene(root);
// sceneNewDate.getStylesheets().add(getClass().getResource("Style.css").toExternalForm());
newDate.setTitle("Neuer Termin");
newDate.setScene(sceneNewDate);
newDate.show();
}
public void createNewDate() throws IOException {
// Termine meinTermin = new Termine(Integer.parseInt(newDateTag.getValue()), Integer.parseInt(newDateMonat.getValue()), Integer.parseInt(newDateJahr.getText()), newDateTitel.getText(), newDateNotiz.getText(),
// Integer.parseInt(newDateStunde.getValue()), Integer.parseInt(newDateMinute.getValue()));
//Add item to ListView
listItems.add("test"); <- this doesnt work
}
public void closeDialogue(){
Stage stage = (Stage) cancelButtonNewDate.getScene().getWindow();
stage.close();
}
}
答案 0 :(得分:0)
执行此操作的一种方法是将listItems
传递给newDate.fxml
的控制器,这样它就可以添加到该列表中。因此,假设newDate.fxml
的控制器类为NewDateController
,您可以执行以下操作:
public class NewDateController {
private ObservableList<String> data ;
public void setData(ObservableList<String> data) {
this.data = data ;
}
// other code as before...
// button handler:
@FXML
private void handleButtonPress() {
data.addItem("test");
}
}
然后在你的ClientGUIController
中,像这样加载fxml:
public void newDate() {
Stage newDate = new Stage();
Parent root;
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("newDate.fxml"));
root = loader.load();
NewDateController controller = loader.getController();
controller.setData(listItems);
} catch (IOException e) {
e.printStackTrace();
return;
}
Scene sceneNewDate = new Scene(root);
newDate.setTitle("Neuer Termin");
newDate.setScene(sceneNewDate);
newDate.show();
}