[英]How do I skip the first index in an enhanced-for loop, when the loop is of type “javafx.scene.control.Tab”?
我正在嘗試設置TabIds,每個選項卡都從名為EntityList的列表中獲取其ID和文本。 問題在於選項卡的數量取決於此EntityList的大小+一個附加的第一個選項卡(用戶在其中輸入entityList),並且一切工作正常,但第一個選項卡應始終命名為“概述”。
我知道如何進行設置,但是我不知道如何跳過Enhanced-for循環中的第一個選項卡(以便它從第二個選項卡開始設置ID,該選項卡將包含EntityList的第一個字符串)。 以下是我的方法:
@FXML
public void currentTabIndex() {
ObservableList<Tab> tabID = mainTabPane.getTabs();
int i=0;
//tabID.get(0).setId("Overview"); --> can't figure out where this should be placed
//tabID.get(0).setText("Overview"); --> and this too
for (Tab loop:tabID) {
for(;i<tabID.size()-1;) {
loop.setId(entityList.get(i).getEntitytName());
loop.setText(entityList.get(i).getEntitytName());
i++;
break;
}
}
}
使用增強的for循環,就不可能跳過第一次迭代。 可以通過引入檢查來解決此問題,但我建議使用其他方法:
您可以使用迭代器使用常規的for循環
for (Iterator<Tab> iterator = tabID.listIterator(1); iterator.hasNext();) {
Tab loop = iterator.next();
...
}
或遍歷子列表:
for (Tab loop : tabID.subList(1, tabID.size())) {
...
}
Stream提供了一種適合您的情況的方法,您可以使用以下跳過方法從OvbservableList
獲取stream()
:
tabID.stream().skip(1).forEach(loop->{
loop.setId(entityList.get(i).getEntitytName());
loop.setText(entityList.get(i).getEntitytName());
i++;
});
skip
參數:要從1開始跳過的前導元素的數量。
編輯:基於@Radiodef評論
由於某些原因,如果您發現需要增強的for
循環,可以將代碼轉換為:
for (Tab loop : (Iterable<Tab>) tabID.stream().skip(1)::iterator) {
......
}
一個簡單的解決方案是添加一個變量來跟蹤是否處理了第一個索引,如果沒有,則跳過該循環迭代。
為此,請更改以下代碼:
for (Tab loop:tabID) {
for(;i<tabID.size()-1;) {
loop.setId(entityList.get(i).getEntitytName());
loop.setText(entityList.get(i).getEntitytName());
i++;
break;
}
}
對此代碼:
boolean skippedFirst = false;
for (Tab loop:tabID) {
if(!skippedFirst){
skippedFirst = true;
}else {
for(;i<tabID.size()-1;) {
loop.setId(entityList.get(i).getEntitytName());
loop.setText(entityList.get(i).getEntitytName());
i++;
break;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.