Search code examples
javalibgdx

How to add a callback to actor when it is added to stage?


I have an Actor that add into the stage at certain time. And a computation of value are needed after it is added to stage. Is there a way to add a callback to the Actor after it is added to stage?

Example Code

public class SlotReel extends Table{

    public SlotReel() {
    }

    public void compute(){
        //call after SlootReel is added to stage
    }

}

Example Stage adding code

stage.addActor(slotReel);// I wish to trigger the compute method in SlotReel after here.

Solution

  • Example

    public class Solution {
    
        // Create interface
        interface Computable {
            void compute();
        }
    
        // SlotReel implement Computable interface
        static public class SlotReel implements Computable {
    
            String name;
    
            public SlotReel(String name) {
                this.name = name;
            }
    
            // Implement compute method
            @Override
            public void compute() {
                // call after SlootReel is added to stage
                // Just an example
                System.out.println("Hello " + name);
            }
    
        }
    
        static public class Stage {
    
            List<Computable> list = new ArrayList<>();
    
            public void addActor(Computable slot) {
                list.add(slot);
                // call compute method
                slot.compute();
            }
        }
    
        public static void main(String[] args) {
            Stage stage = new Stage();
            stage.addActor(new SlotReel("A"));
            stage.addActor(new SlotReel("B"));
            stage.addActor(new SlotReel("C"));
            stage.addActor(new SlotReel("D"));
        }
    }