Java自定义组件

时间:2016-12-15 10:34:34

标签: java user-interface components game-engine

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

我希望自己足够清楚:)

1 个答案:

答案 0 :(得分:0)

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

在矩形类中,您有实现,在组件类中,您创建一个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();
   }
}

对不起我英语能力差,我希望你能理解我的意思^^'