为什么cardlayout键作为对象传递?

时间:2014-04-28 20:46:43

标签: java swing enums cardlayout

java.awt.CardLayout.addLayoutComponent(Component comp, Object constraints)

"约束指定的对象必须是字符串"来自docs.oracle documentation

那么,如果对象必须是字符串,为什么此方法将对象作为参数?问题是唠叨我,因为它让我希望有一种简单的方法可以使用枚举作为卡布局的关键。

public class MainWindow extends JPanel {

private CardLayout cards = new CardLayout();

public MainWindow() {
    setLayout(cards);
    cards.addLayoutComponent(new FirstComp(), MyEnum.LONG_ANNOYING_NAME_ONE);
    cards.addLayoutComponent(new SecondComp(), MyEnum.LONG_ANNOYING_NAME_TWO);
    cards.addLayoutComponent(new ThirdComp(), MyEnum.LONG_ANNOYING_NAME_THREE);
    /**
     * notice no .toString() call on enums. Is there a way to define my
     * enum class so that this functionality is possible?
     **/
}

public void showMethod(MyEnum show) {
    cards.show(this, MyEnum);
}
}

public enum MyEnum {

    LONG_ANNOYING_NAME_ONE, LONG_ANNOYING_NAME_TWO, LONG_ANNOYING_NAME_THREE

}

2 个答案:

答案 0 :(得分:1)

LayoutManager2定义了addLayoutComponent(Component,Object)。第二个参数是Object,因为不同的布局管理器可以支持不同类型的约束。 CardLayout实现了LayoutManager2,因此它必须实现定义的方法。

答案 1 :(得分:1)

由于javadoc声明约束Object必须是String。

但是,没有什么能阻止你扩展CardLayout,并按照你希望的方式重新实现该方法:

public class MyCardLayout extends CardLayout {

    @overrive
    public void addLayoutComponent(Component comp, Object constraints) {

       if  (constraints != null) {
         super.addLayoutComponent(comp, constraints.toString());
       } else {
         super.addLayoutComponent(comp, constraints);
       }
    }
}