Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to add JPanel to a JLabel, under what circumstance, this situation can arise?

Today while surfing through various questions, I encountered one QUESTION, 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 ?

like image 756
nIcE cOw Avatar asked Dec 17 '22 01:12

nIcE cOw


1 Answers

An animated image as a BG for the GUI. I use HTML to resize this one (x3), but if it is already the desired size, you could set it directly as the Icon of the label.

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

Not sure if it is 'genuine' or not. That seems a subjective term that requires much clarification. I've never used this method and only just figured it out, fumbling around tonight. ;)

like image 127
Andrew Thompson Avatar answered Apr 29 '23 06:04

Andrew Thompson