【问题标题】:Java custom componentJava 自定义组件
【发布时间】:2017-04-30 22:16:07
【问题描述】:

我正在尝试用 java 开发一个小型 2d 游戏。我的代码中的所有对象都扩展了 Rectangle 以避免重写关于交叉点、移动等的几何代码。我的下一个问题是绘制我的所有对象。目前我设计了一个 Renderer 类来清除背景并重绘所有对象。另一方面,我观察到对于添加到面板的 java 组件,这是自动完成的(一旦添加了组件,每当我修改它的位置时,组件都会自行更新)。 我的下一个想法是用 Component 扩展我的对象类,但我不能这样做,因为我已经用 Rectangle 扩展了它。 我应该如何解决这个问题?

我希望我说得够清楚:)

【问题讨论】:

    标签: java user-interface components game-engine


    【解决方案1】:

    您可以使用委托模式来实现这一点: 使用 IRectangle 接口,您可以在其中编写 Rectangle 类具有的所有方法。在这种情况下,Rectangle 和您的 Component 类必须实现 IRectangle。

    在 rectangle 类中你有你的实现,在你的组件类中,你创建一个 Rectangle 实例或将它提供给你的构造函数,并且在所有方法中你必须编写因为接口,你可以从 Rectangle 中调用实例。

    示例:

    public interface IRectangle{
       public int getWidth();
       ...
    }
    public class Rectangle implements IRectangle{
       ...
       public int getWidth(){
           return this.width;
       }
    }
    public class CustomComponent extends Component implements IRectangle{
       private Rectangle rect;
       public CustomComponent(Rectangle rect){
            this.rect = rect;
       }
       ...
       public int getWidth(){
           return this.rect.getWidth();
       }
    }
    

    对不起,我的英语水平很差,希望你能明白我的意思^^'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-13
      • 2015-01-04
      • 2015-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      • 1970-01-01
      相关资源
      最近更新 更多