Java LayeredPane LayoutManager add()方法冲突 [英] Java LayeredPane LayoutManager add() Method Conflict

查看:94
本文介绍了Java LayeredPane LayoutManager add()方法冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为 mainPanel JLayeredPane ,它使用的是 BorderLayout .我还有一个名为 backgroundLabel JLabel ,其中包含一个图像.如何将 backgroundLabel 添加到 mainPanel 的最底层?

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));

上面的一行似乎是显而易见的答案,并且如果 mainPanel 使用的是空布局,它将可以正常工作. mainPanel 中的 BorderLayout 不喜欢该命令,并提供以下堆栈跟踪.

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)

如何在不与 BorderLayout 冲突的情况下将 backgroundLabel 添加到 mainPanel 的底层?

How would I go about adding the backgroundLabel to the bottom layer of the mainPanel without conflicting with the BorderLayout?

推荐答案

如何使用分层窗格:在分层窗格中布置组件 ,"Java平台提供的所有布局管理器都将组件布置得好像它们都是在一层上."您已指定 BorderLayout .您对 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);

我的意图是将 backgroundLabel 添加到它在所有其他组件之后的自己的底层.

My intent is for the backgroundLabel to be added to it's own bottom layer behind all other components.

JLayeredPane 上设置布局将使组件好像都位于一层上".而是在占据最深层的组件上设置布局,然后将标签添加到该组件.在此示例中,将标签和按钮添加到具有默认 FlowLayout .

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.

这篇关于Java LayeredPane LayoutManager add()方法冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆