text on top of an image in a component
How do I get text on top of an image in a component?
ImageIcon icon =new ImageIcon("foo.jpg");
JLabel label =new JLabel();
label.setIcon(icon);
// this prints next to, not on top of, the image
label.setText("Hello");
if I add this:
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setVerticalAlignment(SwingConstants.CENTER);
The text doesn't appear at all. I assume it is "underneath" the image.
null
# 1
JPanel panel = new JPanel(null);
panel.setLayout(new BoxLayout(panel,BoxLayout.PAGE_AXIS)));
panel.add(new JLabel("label"));
panel.add(imageIcon);
# 4
> if I add this:
> label.setHorizontalAlignment(SwingConstants.CENTER);
> label.setVerticalAlignment(SwingConstants.CENTER);
The alignment methods determine the position of the component in the parent container, if the layout manager respects those values.
I believe you want:
JLabel label = new JLabel("Some Centered Text");
label.setIcon( new ImageIcon("?.jpg") );
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.CENTER);