2017-05-27 4 views
0

私はそれがよく言われていないことを知っていますが、私はそれをよりよく言葉にする方法を知らない。基本的に私自身の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(); 
}  

私はどのようにラムダわかりません彼らがこの状況に適応できるかどうか、それは多分でしょうか?

+0

あなたは抽象クラスを意味していますか? JComponentから継承した抽象クラスを作成し、ペイントしたpaintComponentメソッドをオーバーライドし、抽象クラスで定義された抽象メソッドを最後に呼び出すことができます – Pali

答えて

1

んラムダが、関数インタフェースは、あなたが行うことができます

に動作します:

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

静的でない関数を与えることは可能ですか? – doominabox1

+1

もちろん、2分で編集して –

関連する問題