问题
Suppose I have a JLayeredPane
called mainPanel
that is using a BorderLayout
. I also have a JLabel
called backgroundLabel
that contains an image. How would I go about adding the backgroundLabel
to the bottom layer of mainPanel
?
mainPanel.add(backgroundLabel, new Integer(-1), new Integer(0));
The above line seems like the obvious answer, and would work if the mainPanel
was using a null layout. The BorderLayout
in mainPanel
is not liking the command and gives the following stack trace.
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: cannot add to layout: constraint must be a string (or null)
at java.awt.BorderLayout.addLayoutComponent(Unknown Source)
at java.awt.Container.addImpl(Unknown Source)
How would I go about adding the backgroundLabel
to the bottom layer of the mainPanel
without conflicting with the BorderLayout
?
回答1:
As noted in How to Use Layered Panes: Laying Out Components in a Layered Pane, "All of the layout managers provided by the Java platform arrange the components as if they were all on one layer." You have specified BorderLayout
. Your call to add() invokes addImpl(java.awt.Component, java.lang.Object, int). Because BorderLayout
implements LayoutManager2
, your value for the constraints
parameter must be a String
constraint defined for BorderLayout, not an Integer
having the value -1
, e.g.
mainPanel.add(backgroundLabel, BorderLayout.SOUTH, 0);
My intent is for the
backgroundLabel
to be added to it's own bottom layer behind all other components.
Setting a layout on the JLayeredPane
makes "the components as if they were all on one layer." Instead, set a layout on the component occupying the deepest layer, and add the label to that component. In this example, a label and button are added to each layer's JPanel
having the default FlowLayout
.
来源:https://stackoverflow.com/questions/37376915/java-layeredpane-layoutmanager-add-method-conflict