无论如何要在JFrame中的图片内添加文本吗? [英] Is there anyway to add text inside picture in JFrame?

查看:22
本文介绍了无论如何要在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);
            }
        });
    }
}

这篇关于无论如何要在JFrame中的图片内添加文本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆