知道居中时 jLabel 中的图像与 jLabel 顶部之间的距离

Knowing the distance between an image in a jLabel and the top of the jLabel when it is centered

我是新来的

我有一个固定大小的 JLabel 和一个用 JLabel.CENTER 放置的图像。我想知道它是如何放置图像的,例如当图像的宽度为 49px 而标签的宽度为 50px 时。 像素是在标签的开头还是结尾。

here the image in the jLabel (the jLabel has a border) the real image

感谢那些愿意花时间阅读本文的人

无法保证当多余像素数为奇数时,JLabel 的图标将如何居中。当然,您可以观察当前的行为,但不能保证以后的 Java 版本不会有不同。

如果你想确定,可以创建一个JPanel的子类,重写paintComponentgetPreferredSize方法,自己绘制图像:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import javax.swing.JPanel;

public class ImagePanel
extends JPanel {
    private static final long serialVersionUID = 1;

    private Image image;

    public ImagePanel(Image image) {
        this.image = image;
    }

    @Override
    public Dimension getPreferredSize() {
        Insets insets = getInsets();
        Dimension size = new Dimension(
            insets.left + insets.right, insets.top + insets.bottom);

        if (image != null) {
            int width = image.getWidth(this);
            int height = image.getHeight(this);

            size.width += Math.max(width, 0);
            size.height += Math.max(height, 0);
        }

        return size;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        if (image != null) {
            int width = image.getWidth(this);
            int height = image.getHeight(this);
            if (width > 0 && height > 0) {
                int widthDifference = getWidth() - width;

                int x = widthDifference / 2;
                if (widthDifference % 2 != 0) {
                    // If you want the extra space on the left:
                    //x++;
                }

                int y = (getHeight() - height) / 2;

                g.drawImage(image, x, y, this);
            }
        }
    }
}