Is there a way to loop through Control array and get only one type of UI elements, for example, TextField
s? Here is an array which contains TextField
s, DatePicker
s, and ChoiceBox
es:
Control[] allControls = new Control[] {
name, surname, age, address, city,
telephoneNum, email, deptBox, idNum, startDate,
contractType, endDate, payFreq, accountNum, taxCoeficient,
netSalary
};
Is there a way to put if
condition in for
loop and get only one type of UI elements?
答案 0 :(得分:2)
You can apply the Stream API to filter all instance being of the desired class using instanceof
and finally collect them to a new List:
List<TextField> textFieldList = Arrays.asList(allControls).stream()
.filter(c -> c instanceof TextField)
.map (c -> (TextField) c)
.collect(Collectors.toList());
答案 1 :(得分:1)
You ca use instanceof
with a loop like this :
List<Control> list = new ArrayList<>();
for(Control item : allControls){
if(item instanceof TextField){
list.add(c);
}
}
Edit
Can you use getText() method on items from new list? How to access values of Control items?
Yes you can cast your item to TextField
then you can use getText()
like this :
List<TextField> list = new ArrayList<>();
for (Control item : list) {
String text = ((TextField) item).getText();
System.out.println(text);
}
To avoid all this you can create a List of TextField
from begginig like this :
List<TextField> list = new ArrayList<>();
for (Control item : allControls) {
if (item instanceof TextField) {
list.add((TextField) item);
}
}
So you can easily use item.getText()
without casting.