无论如何要在JFrame中的图片内添加文本吗?

2022-01-24 00:00:00 image text java swing jframe

该死,我的英语有点不对劲.我的意思是问如何在图片内部"添加文字而不是在它上面(上面),文字位于图片的中心.无论如何,谢谢你以前的帮助:).

Damn, my english is a bit off. I meant to ask how to add text "inside" picture not over(above) it , with the text be at the center of picture. thank you for previous helps anyway :).

推荐答案

一种方法是使用 OverlayLayout.对于要在两个轴上位于图像中心的文本,0.5 的对齐值应该用于 X 和Y 对于两个 JLabel 组件如下所示.

One way is to use OverlayLayout. For the text to be at the center of the image in both axes an alignment value of 0.5 should be used for both X & Y for both JLabel components shown below.

public class OverlayLabelApp {
    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new JFrame("Overlay App");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                JPanel panel = new JPanel();

                LayoutManager overlay = new OverlayLayout(panel);
                panel.setLayout(overlay);

                JLabel label1 = new JLabel("Centered Text");
                label1.setForeground(Color.GREEN);
                label1.setFont(new Font("SansSerif", Font.BOLD, 16));
                label1.setAlignmentX(0.5f);
                label1.setAlignmentY(0.5f);
                panel.add(label1);

                JLabel label2 = 
                  new JLabel(new ImageIcon(OverlayLabelApp.class.getResource("/images/sunset.png")));                   label2.setAlignmentX(0.5f);
                label2.setAlignmentY(0.5f);
                panel.add(label2);

                frame.add(panel);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}

相关文章