我知道措辞不好,但我不知道如何更好地说出来。基本上我有自己的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();
}
我不确定lambdas是如何工作的,或者它们是否适用于这种情况,但可能是吗?
答案 0 :(得分:1)
没有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
}
}