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

[629 byte] By [allelopatha] at [2007-11-27 6:51:45]
# 1

JPanel panel = new JPanel(null);

panel.setLayout(new BoxLayout(panel,BoxLayout.PAGE_AXIS)));

panel.add(new JLabel("label"));

panel.add(imageIcon);

Nethera at 2007-7-12 18:26:14 > top of Java-index,Desktop,Core GUI APIs...
# 2
Thanks for your reply.There is a problem. imageIcon is not a component, so a compile error is generated with the Container.add(component) method.
allelopatha at 2007-7-12 18:26:14 > top of Java-index,Desktop,Core GUI APIs...
# 3
wrap it in a JLabelJLabel label = new JLabel(imageIcon);
Nethera at 2007-7-12 18:26:15 > top of Java-index,Desktop,Core GUI APIs...
# 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);

camickra at 2007-7-12 18:26:15 > top of Java-index,Desktop,Core GUI APIs...
# 5
That works, thanks.
allelopatha at 2007-7-12 18:26:15 > top of Java-index,Desktop,Core GUI APIs...