1

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?

0

2 Answers 2

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());
Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

Can you use getText() method on items from new list? How to access values of Control items?
@Kvark900 you can cast your item to (TextField) item so you can use getText() like ((TextField) item).getText()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.