解决2类扩展问题

时间:2020-06-21 12:59:35

标签: java user-interface

我知道标题很混乱。 我想使用swing创建自己的Java UI库。我首先决定创建一个UIButton。

代码(非常简化):

class UIButton extends JButton {
int x = DEFAULT_X, y = DEFAULT_Y;
int w = DEFAULT_w, h = DEFAULT_H;
UIButton(){
  super("Text Here");
  super.setBounds(x,y,w,h);
}

void setPosition(int x, int y){
  this.x = x;
  this.y = y;
  super.setBounds(x,y,w,h);
}

void setDimensions(int w, int h){
  this.w = w;
  this.h = h;
  super.setBounds(x,y,w,h);
}

void enableMe(){
  super.setVisible(false);
  super.setEnabled(false);
  super.setFocusable(false);
}
...
}

然后我意识到代码会重复,因为每个UI组件都需要setPosition,setDimensions和enableMe(),所以我制作了一个类UIComponent,但是您无法编写class UIButton extends JButton, UIComponent {...} :( 然后,我创建了一个接口UIComponentInter,在其中放置了所有默认方法,该方法可以与enableMe()方法一起正常工作,但其余部分则无法使用。 UIComponentInter(如果子类不是JComponent的一部分,则必须变通):

default void enableMe(){
  if(!(this instanceof JComponent)) return;
  JComponent component = (JComponent) this;
  component.setVisible(true);
  component.setEnabled(true);
  component.setFocusable(true);
}

setPosition()方法需要变量x和y,但是接口中的每个变量都是最终变量和静态变量。

当前,我使用UIComponent类来控制行为,而UIButton类充当UIComponent的代理,但是我仍然必须复制粘贴很多代码以添加新的UI元素。

1 个答案:

答案 0 :(得分:-1)

使用组合而不是继承-使您的类具有JButton类型的实例字段– user