1

我试图让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);

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

4

3 回答 3

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

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

于 2012-12-12T14:03:30.560 回答
2

下方带有文字的图标

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);
    }
}
于 2012-12-12T14:10:40.640 回答
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));
于 2012-12-12T14:32:25.973 回答