为什么要将JPanel添加到JLabel,在什么情况下会出现这种情况?

今天在浏览各种问题的同时,我遇到了一个问题 ,这在我看来有点奇怪,为什么要将一个JPanel添加到JLabel ,是否有任何真正的理由可以出现这种情况,那么这只是微不足道的吗?

动画图像作为GUI的BG。 我使用HTML来调整这个(x3)的大小,但是如果它已经是所需的大小,你可以直接将它设置为标签的Icon

 import java.awt.*; import javax.swing.*; import javax.swing.border.EmptyBorder; class LabelAsBackground { public static final String HTML = "" + "" + "" + "" + ""; LabelAsBackground() { JFrame f = new JFrame("Animated Image BG"); f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JLabel contentPane = new JLabel(HTML); contentPane.setLayout(new GridLayout()); JPanel gui = new JPanel(new GridLayout(3,3,15,15)); gui.setOpaque(false); contentPane.add(gui); gui.setBorder(new EmptyBorder(20,20,20,20)); for (int ii=1; ii<10; ii++) { gui.add( new JButton("" + ii)); } f.setContentPane(contentPane); f.pack(); //f.setResizable(false); // uncomment to see strange effect.. f.setVisible(true); } public static void main(String[] args) { //Create the frame on the event dispatching thread SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { LabelAsBackground lab = new LabelAsBackground(); } }); } } 

不确定它是否“真实”。 这似乎是一个主观术语,需要进行大量澄清。 我从来没有使用过这种方法,只是想出来,今晚摸索着。 ;)

 this seems to me a bit weird, why would one wants to add a JPanel to a JLabel, 

恩,那就对了

 are there any genuine reasons as to such situation can arise, so is it just trivial? 

不,不是微不足道的,因为只有JFrame / JDialog / JWindowJPanel有pre_implemented LayoutManager ,对于“ Custom JComponent ”的其余部分, 你必须以编程方式声明正确的LayoutManager

是的,有充分的理由想要将组件添加到JLabel。 由于在JLabel上设置和交换ImageIcons非常容易,因此想要将它们用作GUI的后备映像并不罕见。

编辑
你说:

啊哈的意思是说,如果我希望我的容器具有特定的背景,那么我必须使用JLabel作为平台,这样的东西可以驻留在哪里? 我对吗 ?

不,你不必绝对使用JLabel,因为如果需要,在JPanel中绘制背景图像相当容易。 只需在paintComponent(...)方法中绘制图像。