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

时间:2012-04-13 12:27:00

标签: java swing jpanel jlabel

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

3 个答案:

答案 0 :(得分:5)

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已经预先实现LayoutManager,其余为“{{ 1}}“you have to declare proper LayoutManager, programatically

答案 1 :(得分:4)

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

修改
你说:

  

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

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

答案 2 :(得分:4)

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

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

class LabelAsBackground {

    public static final String HTML =
        "<html>" +
        "<style type'text/css'>" +
        "body, html { padding: 0px; margin: 0px; }" +
        "</style>" +
        "<body>" +
        "<img src='http://pscode.org/media/starzoom-thumb.gif'" +
        " width=320 height=240>" +
        "";

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

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