Getting UI elements by type from Control array?

时间:2017-08-13 13:54:46

标签: java arrays for-loop if-statement javafx

Is there a way to loop through Control array and get only one type of UI elements, for example, TextFields? Here is an array which contains TextFields, DatePickers, and ChoiceBoxes:

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?

2 个答案:

答案 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.