我想在Tableview中计算不同的状态并将其显示在标签中。是否有办法实现此功能,而无需在每次值更改时迭代整个列表?有没有办法将不同状态的数量绑定到标签?
目前我正在迭代List:
private void updateLbl(){
int on = 0, off = 0, un = 0;
for(StringContainer wps : streamLinkList){
if(wps.getState().equals("online")){
on++;
} else if(wps.getState().equals("offline")){
off++;
} else if(wps.getState().equals("unknown")){
un++;
} else {
se++;
}
}
onLbl.setText("Online: " + on);
offLbl.setText("Offline: " + off);
unLbl.setText("Unknown: " + un);
}
编辑:
List是一个ObservableList。 StringContainer包含不同的StringPropertys。
class StringContainer{
private StringProperty state;
public StringContainer(){
this.state = new SimpleStringProperty();
}
// state
public void setState(String state){
this.state.set(state);
}
public String getState(){
return state.get();
}
public StringProperty stateProperty(){
return state;
}
}
答案 0 :(得分:1)
您可以按以下方式执行操作:
ObservableList<StringContainer> items = table.getItems();
// initialize counts (only needed once, and only if items is non-empty):
int on = off = unk = 0 ;
for (StringContainer item : items) {
if ("online".equals(item.getState())) on++ ;
if ("offline".equals(item.getState())) off++ ;
if ("unknown".equals(item.getState())) unk++ ;
}
IntegerProperty onCount = new SimpleIntegerProperty(on);
IntegerProperty offCount = new SimpleIntegerProperty(off);
IntegerProperty unknownCount = new SimpleIntegerProperty(unk);
onLbl.textProperty().bind(onCount.asString("Online: %s"));
offLbl.textProperty().bind(offCount.asString("Offline: %s"));
unLbl.textProperty().bind(unknownCount.asString("Unknown: %s"));
ChangeListener<String> listener = (obs, oldValue, newValue) -> {
if ("online".equals(oldValue)) onCount.set(onCount.get() - 1);
if ("offline".equals(oldValue)) offCount.set(offCount.get() - 1);
if ("unknown".equals(oldValue)) unknownCount.set(unknownCount.get() - 1);
if ("online".equals(newValue)) onCount.set(onCount.get() + 1);
if ("offline".equals(newValue)) offCount.set(offCount.get() + 1);
if ("unknown".equals(newValue)) unknownCount.set(unknownCount.get() + 1);
};
items.forEach(item -> item.stateProperty().addListener(listener));
items.addListener((ListChangeListener.Change<? extends StringContainer> c) -> {
while (c.next()) {
if (c.wasAdded()) {
for (StringContainer item : c.getAddedSubList()) {
item.stateProperty().addListener(listener);
if ("online".equals(item.getState())) onCount.set(onCount.get() + 1) ;
if ("offline".equals(item.getState())) offCount.set(offCount.get() + 1) ;
if ("unknown".equals(item.getState())) unknownCount.set(unknownCount.get() + 1) ;
}
}
if (c.wasRemoved()) {
for (StringContainer item : c.getRemoved()) {
item.stateProperty().removeListener(listener);
if ("online".equals(item.getState())) onCount.set(onCount.get() - 1) ;
if ("offline".equals(item.getState())) offCount.set(offCount.get() - 1) ;
if ("unknown".equals(item.getState())) unknownCount.set(unknownCount.get() - 1) ;
}
}
}
});