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
this seems to me a bit weird, why would one wants to add
a JPanel to a JLabel,
yes thats right
are there any genuine reasons as to such situation can arise,
so is it just trivial?
no, isn't trivial, because only JFrame
/JDialog
/JWindow
and JPanel
have got pre_implemented LayoutManager
, for rest of "Custom JComponent
" you have to declare proper LayoutManager, programatically
Yes there are genuine reasons to want to add components to a JLabel. Since it is trivially easy to set and swap ImageIcons on JLabels, it's not uncommon to want to use them as a backing image for your GUI.
Edit
You state:
Ahha mean to say, If I wanted my container to have a specific background, then I must be using JLabel as the platform, on which such things can reside ? Am I right ?
No, you don't absolutely have to use a JLabel for this as it is fairly easy to draw a background image in a JPanel if desired. Just draw the image in its paintComponent(...)
method.
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. ;)