2017-05-27 150 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(); 
}  

我不知道如何lambda表達式工作還是適用於這種情況,但也許呢?

+0

你的意思是抽象類?你可以創建一個從JComponent繼承的抽象類,並重寫paintComponent方法,並在最後一次調用時調用抽象類定義的抽象方法 – Pali

回答

1

沒有lambda表達式,但功能界面將工作

你可以這樣做:

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分鐘內編輯,告訴你如何 –