local variables referenced from a lambda expression must be final or effectively final

前端 未结 3 408
情深已故
情深已故 2020-12-10 11:10

I have a JavaFX 8 program (for JavaFXPorts cross platfrom) pretty much framed to do what I want but came up one step short. The program reads a text file, counts the lines

3条回答
  •  被撕碎了的回忆
    2020-12-10 11:19

    I regularly pass outer object into interface implementation in this way: 1. Create some object holder, 2. Set this object holder with some desired state, 3. Change inner variables in the object holder, 4. Get those variables and use them.

    Here is one example from Vaadin :

    Object holder : 
        public class ObjectHolder {
        private T obj;
        public ObjectHolder(T obj) {
            this.obj = obj;
        }
        public T get() {
            return obj;
        }
        public void set(T obj) {
            this.obj = obj;
        }
    }
    

    I want to pass button captions externally defined like this :

    String[] bCaption = new String[]{"Start", "Stop", "Restart", "Status"};
    String[] commOpt = bCaption;
    

    Next, I have a for loop, and want to create buttons dynamically, and pass values like this :

    for (Integer i = 0; i < bCaption.length; i++) {
        ObjectHolder indeks = new ObjectHolder<>(i);
        b[i] = new Button(bCaption[i], 
            (Button.ClickEvent e) -> {
                remoteCommand.execute(
                    cred, 
                    adresaServera, 
                     comm + " " + commOpt[indeks.get()].toLowerCase()
                 );
             }
            );
    
            b[i].setWidth(70, Unit.PIXELS);
            commandHL.addComponent(b[i]);
            commandHL.setComponentAlignment(b[i], Alignment.MIDDLE_CENTER);
      }
    

    Hope this helps..

提交回复
热议问题