[英]Reference control by fx:id
我有一個使用 JavaFX 和 Scene Builder 為 class 設計的日歷屏幕。
我放置數字的部分是 label,而當前顯示“無”的部分是一個按鈕。 我想在 select Button 時引用 Label 中的值,以便我可以顯示當天用戶的約會。
有沒有辦法通過 FX:ID 字符串名稱來引用控件,以便我可以這樣做? Label 稱為 lblDayOfTheWeekxx,按鈕稱為 btnAppointmentxx,其中 xx 是從 01 到 42 的值。
這就是我嘗試更改值的方法。 這只是一個測試,我試圖將第一個按鈕的值變為“完成”。
@FXML
void handleDayChosen(ActionEvent event) {
try {
// FXMLLoader loader = new FXMLLoader();
// loader.setLocation(getClass().getResource("/Views/FormMain.fxml"));
// Parent myView = loader.load();
// Scene myScene = new Scene(myView);
// Label lbl = (Label) myScene.lookup("#lblDateOfMonth01");
// Label myLblField = (Label)myView.FindControl("txtField" + 1);
// lbl.setText("DONE");
FXMLLoader loader = new FXMLLoader(getClass().getResource("/Views/FormMain.fxml"));
Parent root = loader.load();
Button foo = (Button)loader.getNamespace().get("lblAppointments01");
foo.setText("DONE");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
我是 Java 的新手,所以我不知道自己做錯了什么。
提前致謝,
賬單
這是我最終想到的。 我知道它不漂亮但它有效。
GridPane gpCal = this.gpCalendar;
for (int i = 1 ; i <= 7; i++) {
int row = i * 2;
for (int col = 1; col <= 7; col++) {
int pos = ((i-1)*7)+col;
lblDay[pos] = new Label();
lblDay[pos].setText("");
lblDay[pos].setPrefSize(100, 20);
lblDay[pos].setText(String.valueOf(col) + ", " + String.valueOf(row));
gpCal.add(lblDay[pos], col, row);
}
row++;
for (int col = 0; col <= 6; col++) {
int pos = ((i-1)*7)+col;
btnAppts[pos] = new Button();
btnAppts[pos].setText("");
btnAppts[pos].setPrefSize(100, 100);
btnAppts[pos].setText(String.valueOf(col) + ", " + String.valueOf(row));
gpCal.add(btnAppts[pos], col, row);
}
}
現在是格式化按鈕和標簽以匹配下面的簡單部分。
謝謝您的幫助,
賬單
像這樣的 UI 根本不適合 FXML。 使用 Java 創建這樣的 UI 通常更容易,代碼也更少。這樣您就可以在循環中創建按鈕和 label,並為每個添加不同的事件處理程序:
int numDays = 30 ; // in real life this comes from the month and year
GridPane calendarPane = ...; // can be a @FXML-injected variable if needed
for (int i = 1 ; i <= numDays ; i++) {
Label dayLabel = new Label(Integer.toString(i));
Button button = new Button("None");
// set styles, etc
int day = i ;
button.setOnAction(e -> processButtonPress(button, dayLabel, day));
VBox vbox = new VBox(dayLabel, button);
int row = getRowForDay(i);
int col = getColumnForDay(i);
calendarPane.add(vbox, col, row);
}
// ...
private void handleDayChosen(Button button, Label label, int dayOfMonth) {
// whatever you need here...
label.setTextFill(Color.GREEN);
button.setText("Done");
}
顯然,如果需要,您仍然可以對周圍的 UI 使用 FXML,只需將上面的循環放在控制器的initialize()
方法中即可。 但這顯然比 100 多行 FXML 加上 controller 中的 60 個不同變量來實現同樣的事情要好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.