Reputation:
While using JLayeredPane to add Compnents in z-order, I noticed some issue:
JLayeredPane lp = getLayeredPane();
JButton top = new JButton(); ...
JButton middle = new JButton(); ...
JButton bottom = new JButton(); ...
Works bad:
lp.add(top,2);
lp.add(middle,1);
lp.add(bottom,3);
Works good:
lp.add(top,new Integer(2));
lp.add(middle,new Integer(1));
lp.add(bottom,new Integer(3));
Here you can see how it looks: https://i.sstatic.net/5TwSJ.png
Why is literal constant not converted into Integer object, and it does not work properly?
Upvotes: 1
Views: 363
Reputation: 324108
Why is literal constant not converted into Integer object, and it does not work properly?
You need to look at the API for the add(...)
method.
The Container
class has a method that accepts an "int" as a parameter. This is used for layouts like the FlowLayout where you can insert a component at a specified position.
The JLayeredPane
class has a method that accepts an "Integer" value to specify the layering of the component.
So you can't depend on autoboxing to convert the int to an Integer.
Upvotes: 3
Reputation: 628
In essence because the class it inherits from (Container) has a function to add a Component at a given position in it's list of components (add(Component comp, int layer)
), as well as a function to add a Component with any given argument (to be passed to the LayoutManager) (add(Component comp, Object constraint)
).
In order for the right function to be called (and JLayeredPane's LayoutManager to receive the constraint) the argumentmust be an Object Integer
and not a primitive int
.
Upvotes: 3