2

yesterday i saw an example of Combo box on oracle site on the link below:
http://docs.oracle.com/javase/8/javafx/user-interface-tutorial/combo-box.htm#BABJCCIB
On this page there is an example under the section named "Applying Cell Factories to Combo Boxes". In this example there is a code i am pasting here:-

priorityComboBox.setCellFactory(
            new Callback<ListView<String>, ListCell<String>>() {
                @Override public ListCell<String> call(ListView<String> param) {
                    final ListCell<String> cell = new ListCell<String>() {
                        {
                            super.setPrefWidth(100);
                        }    
                        @Override public void updateItem(String item, 
                            boolean empty) {
                                super.updateItem(item, empty);
                                if (item != null) {
                                    setText(item);    
                                    if (item.contains("High")) {
                                        setTextFill(Color.RED);
                                    }
                                    else if (item.contains("Low")){
                                        setTextFill(Color.GREEN);
                                    }
                                    else {
                                        setTextFill(Color.BLACK);
                                    }
                                }
                                else {
                                    setText(null);
                                }
                            }
                };
                return cell;
            }
        });


In the above code below code is used to call the super class method setPrefWidth.

{
  super.setPrefWidth(100);
} 

Now my question is why they used the anonymous code block to do this. They can put that statement in the updateItem method.
What is the intention to do this?

0

1 Answer 1

1

Let's say you could insert it into your updateItem-Method but then it would get called every time the item is updated.

This might not be a big Problem with setPrefWidth as nothing changes but imagine you have something like firstInitialize();which is not supposed to be called more than once.

Therefore you can use the Initializer Block. Otherwise you would have to add a variable like bool isInitialized where you check first, if the variable is true and in case it's not, you performe your Action.

You can also have a look at: Initializing Fields

Not the answer you're looking for? Browse other questions tagged or ask your own question.