【问题标题】:Java simplifying draw object pathwaysJava 简化绘制对象路径
【发布时间】:2020-12-06 03:06:11
【问题描述】:

所以,基本上,我正在尝试制作一个函数式接口,以便我可以在不同的绘制操作之间进行选择,而不必写出传递给每个绘制操作的实际变量。我有这个:

public void draw(Graphics g){
    setColor(g);
    Consumer4 c;
    //if (getSolid()) g.fillOval(this.x, this.y, this.width, this.height);
    //else g.drawOval(this.x, this.y, this.width, this.height);
    if (getSolid()) c = (int t,int u,int v,int w) -> g.fillOval(t,u,v,w);
    else c = (t,u,v,w) -> g.drawOval(t,u,v,w);
    g.c(this.x, this.y, this.width, this.height);
}

我创建了这个类来帮助它:(注意它位于抽象超类中)

    @FunctionalInterface
    protected static interface Consumer4{
        //public abstract <T,U,V,W>void accept(T t,U u,V v,W w);
        public abstract void accept(int t,int u,int v,int w);
    }

注释掉的部分是我想要它做的,还要注意我试图用泛型做它,因此我的功能接口的注释掉的部分。

我也试过这个,看看它是否有帮助,以及我的功能界面中的相关更改,但没有运气。

    if (getSolid()) c = (int t,int u,int v,int w,Graphics y) -> y.fillOval(t,u,v,w);
    else c = (t,u,v,w,y) -> y.drawOval(t,u,v,w);
    c(this.x, this.y, this.width, this.height,g);

这可行吗?或者我做错了什么。

【问题讨论】:

    标签: java methods functional-interface


    【解决方案1】:

    Nvm,我想通了……

            if (getSolid()) c = (int t,int u,int v,int w) -> g.fillOval(t,u,v,w);
            else c = (t,u,v,w) -> g.drawOval(t,u,v,w);
            c.accept(this.x, this.y, this.width, this.height);
    

    不过,不管我怎么想,它似乎比它的价值更多的代码,除非 c 被多次使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-15
      • 1970-01-01
      • 1970-01-01
      • 2014-12-25
      • 2013-05-24
      • 2010-11-30
      • 2012-09-13
      • 1970-01-01
      相关资源
      最近更新 更多