2017-05-27 148 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分钟内编辑,告诉你如何 –