Search code examples
javajcomponent

How can I let a class add onto my paint function?


I know that is poorly worded, but I don't know how to word it better. Essentially I have my own JComponent MyComponent and it paints some stuff onto its graphics. I want it to paint its stuff, then call a method to finish the paint, here is an example:

public class MyComponent extends JComponent{
    // etc
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g2 = (Graphics2D)g;
        g2.drawSomething(); // etc

        // Once it is done, check if that function is exists, and call it.
        if(secondaryPaint != null){
            secondaryPaint(g2);
        }
    }
}  

Then, in a different class:

// etc
MyComponent mc = new MyComponent()
mc.setSecondaryDrawFunction(paint);

// etc

private void paint(Graphics2D g2){
    g2.drawSomething();
}    

I'm not sure how lambdas work or if they are applicable in this situation, but maybe that?


Solution

  • No lambdas, but the Function interface will work

    You can do :

    public class MyComponent extends JComponent{
        // etc
        Function<Graphics2D, Void> secondaryPaint;
        public MyComponent(Function<Graphics2D, Void> myfc){
            secondaryPaint = myfc;
        }
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            //g2.drawSomething(); // etc
    
            // Once it is done, check if that function is exists, and call it.
            if(secondaryPaint != null){
                secondaryPaint.apply(g2);
            }
        }
    
        static class Something {
            public static Void compute(Graphics2D g){
                return null;
            }
    
            public Void computeNotStatic(Graphics2D g){
                return null;
            }
        }
    
        public static void main(String[] args) {
            Something smth = new Something();
            new MyComponent(Something::compute); // with static
            new MyComponent(smth::computeNotStatic); // with non-static
        }
    }