如何让 class 添加到我的绘画功能中?
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);
}
}
}
然后,在另一个 class 中:
// 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
}
}
我知道这句话措辞不好,但我不知道怎么说才好。本质上我有自己的 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);
}
}
}
然后,在另一个 class 中:
// 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
}
}