1

I am trying to get the JLabel icon to appear above the text for the label.

Currently I have the following code;

URL loc = null;
        ImageIcon img = null;
        JLabel label = null;

        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

        loc = Test.class.getResource("/Images/imageName.jpg");
        img = new ImageIcon(loc);
        label = new JLabel("someText", img, JLabel.CENTER);
        label.setIconTextGap(0);
        label.setVerticalTextPosition(JLabel.BOTTOM);
        label.setHorizontalTextPosition(JLabel.RIGHT);
        frame.getContentPane().add(label);

The output I currently see is the label text to the right of the image icon. Can anyone suggest what to change?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Biscuit128
  • 5,218
  • 22
  • 89
  • 149

3 Answers3

5
label.setVerticalTextPosition(JLabel.BOTTOM);
label.setHorizontalTextPosition(JLabel.CENTER);

You need to center align on the horizontal axis for the text to appear under the icon.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
2

Icon with text beneath

import java.awt.image.BufferedImage;
import javax.swing.*;

public class TopLabel {

    public static void main(String[] args) throws Exception {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                JLabel label = new JLabel("Text");

                BufferedImage image = new BufferedImage(
                        32,32,BufferedImage.TYPE_INT_RGB);
                label.setIcon(new ImageIcon(image));

                label.setVerticalTextPosition(SwingConstants.BOTTOM);
                label.setHorizontalTextPosition(SwingConstants.CENTER);

                JOptionPane.showMessageDialog(null, label);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
        SwingUtilities.invokeLater(r);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
0

IIUC, and you want to show a text inside (in the middle of) a image/icon then you have an option to use Graphics.drawString() to draw your text inside image.

BufferedImage bimg = ImageIO.read(url);
Graphics2D g = (Graphics2d)img.getGraphics();
g.drawString("Text", x, y); //y > 0
g.dispose();

JLabel label = new JLabel();
label.setIcon(new ImageIcon(bimg));
Nikolay Kuznetsov
  • 9,467
  • 12
  • 55
  • 101