如何将 JLabel 定位在北方但不完全位于顶部?

How do I position a JLabel north but not completely at the top?

我想在图片上放置标签。标签和图像都位于位于中心的面板中。我希望我的标签位于图像上方,但如果我这样做了 BorderLayout.NORTH,它会将标签放置得尽可能远。

如何将它放在我想要的位置,但仍位于图像上方?

在标签中添加一个 EmptyBorder。可以指定所有四个填充整数。在这三个 GUI 中,顶部填充(仅)设置为 0、30 和 60 像素。

import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;

public class LabelPadding {

    private JComponent ui = null;
    static BufferedImage bi = 
            new BufferedImage(400, 10, BufferedImage.TYPE_INT_RGB);

    LabelPadding(int pad) {
        ui = new JPanel(new BorderLayout(4,4));
        ui.setBorder(new EmptyBorder(4,4,4,4));

        JLabel label = new JLabel("The top padding in px is: " + pad);
        label.setBorder(new EmptyBorder(pad, 0, 0, 0));
        ui.add(label, BorderLayout.PAGE_START);
        ui.add(new JLabel(new ImageIcon(bi)));
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(
                            UIManager.getSystemLookAndFeelClassName());
                } catch (Exception useDefault) {
                }
                for (int ii=0; ii<70; ii+=30) {
                    LabelPadding o = new LabelPadding(ii);

                    JFrame f = new JFrame(o.getClass().getSimpleName());
                    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    f.setLocationByPlatform(true);

                    f.setContentPane(o.getUI());
                    f.pack();
                    f.setMinimumSize(f.getSize());

                    f.setVisible(true);
                }
            }
        };
        SwingUtilities.invokeLater(r);
    }
}