簡體   English   中英

如何讓一個類添加到我的繪畫函數中?

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

我知道該詞措辭不佳,但我不知道該如何措辭更好。 本質上,我有自己的JComponent MyComponent ,它在其圖形上繪制了一些東西。 我希望它繪制其內容,然后調用一種方法來完成繪制,這是一個示例:

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);
        }
    }
}  

然后,在另一個類中:

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

// etc

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

我不確定lambda如何工作或在這種情況下是否適用,但是也許可以嗎?

沒有lambda,但是Function接口可以工作

你可以做 :

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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM