繁体   English   中英

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

[英]Getting label icon to appear above text

我正在尝试使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);

我当前看到的输出是图像图标右侧的标签文本。 谁能建议更改什么?

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

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

下方带有文字的图标

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM