簡體   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