【问题标题】:JLayeredPane z-order issueJLayeredPane z 顺序问题
【发布时间】:2016-12-14 10:22:59
【问题描述】:

在使用 JLayeredPane 以 z 顺序添加组件时,我注意到了一些问题:

JLayeredPane lp = getLayeredPane();

JButton top = new JButton(); ...
JButton middle = new JButton(); ...
JButton bottom = new JButton(); ...

效果不佳:

lp.add(top,2);
lp.add(middle,1);
lp.add(bottom,3);

效果很好:

lp.add(top,new Integer(2));
lp.add(middle,new Integer(1));
lp.add(bottom,new Integer(3));

在这里你可以看到它的样子:http://i.imgur.com/eqH2El8.png

为什么字面量常量没有转成Integer对象,不能正常工作?

【问题讨论】:

    标签: java swing type-conversion z-order jlayeredpane


    【解决方案1】:

    本质上,因为它从 (Container) 继承的类具有在其组件列表中的给定位置添加组件的功能 (add(Component comp, int layer)),以及添加具有任何给定参数的组件的功能 (传递给 LayoutManager) (add(Component comp, Object constraint))。

    为了调用正确的函数(以及 JLayeredPane 的 LayoutManager 来接收约束),参数必须是 Object Integer 而不是原始 int

    【讨论】:

      【解决方案2】:

      为什么字面常量没有转成Integer对象,而且不能正常工作?

      您需要查看add(...) 方法的API。

      Container 类有一个接受“int”作为参数的方法。这用于像 FlowLayout 这样的布局,您可以在指定位置插入组件。

      JLayeredPane 类有一个方法,该方法接受一个“整数”值来指定组件的分层。

      因此您不能依赖自动装箱将 int 转换为 Integer。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-29
        • 1970-01-01
        • 2012-07-16
        • 2012-05-11
        • 2013-07-13
        • 2011-01-18
        • 2012-12-24
        相关资源
        最近更新 更多