获取标签图标以显示在文本上方

时间:2012-12-12 13:56:56

标签: java image swing jlabel imageicon

我正在尝试将JLabel图标显示在标签文本的上方。

目前我有以下代码;

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

我目前看到的输出是图像图标右侧的标签文本。任何人都可以建议改变什么?

3 个答案:

答案 0 :(得分:3)

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

您需要在水平轴上居中对齐,以便文本显示在图标下方。

答案 1 :(得分: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);
    }
}

答案 2 :(得分:0)

IIUC,你想在你的图像/图标里面(中间)显示一个文字 使用Graphics.drawString()在图像中绘制文字的选项。

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