简体   繁体   中英

Java: the final local variable cannot be assigned, since it was defined in an enclosing type

How may one fix this problem?

The error lies @ scrollPane and map.

scrollPane error: the final local variable cannot be assigned, since it was defined in an enclosing type

map error suggestion: initialise variable.

final Map<ItemType, JScrollPane> viewScrollPanes = new HashMap<ItemType, JScrollPane>();
final JScrollPane scrollPane;
final Map<ItemType, JScrollPane> map;
this.viewList.forEach((type, list) -> {
  list.setSelectionMode(0);
  list.setVisibleRowCount(5);
  list.putClientProperty("type", type);
  list.setCellRenderer(this.itemRenderer);
  list.setName(String.valueOf(type.toString()) + "List");
  scrollPane = new JScrollPane(list);
  scrollPane.setMinimumSize(new Dimension(0, 110));
  scrollPane.setName(type.toString());
  map.put(type, scrollPane);
  return;
});

You cannot assign to a final variable repeatedly in a loop.

It looks like scrollPane should be a local variable inside of each iteration.

map needs be initialized before you enter the loop (otherwise you cannot put anything in it).

You can't. You define a final variable, which you can store only one and final object. You did a for loop, and for each iteration, you try to assign a new object in scrollpane, but the variable is marked as a final object.

So the only way is to remove the final keyword.

About map, remove the final keyword and put this instead

Map<ItemType, JScrollPane> map = new HashMap<>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM