【问题标题】:How to add text over an image in a JFrame?如何在 JFrame 中的图像上添加文本?
【发布时间】:2015-05-23 18:34:35
【问题描述】:

您好,我想创建一个程序来获取信息并将其显示在自定义位置或我为其设置的点的图像上。我尝试了不同的方法,但它们不起作用或显示框架。基本上,我想知道如何在图像上添加文本。谢谢!

/*
 * This program will ask information to be displayed in four different pieces of documentation.
 */

package choice.assignment;

import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/*
 * @author Talha
 */

public class ChoiceAssignment extends JFrame {

    public static void main(String[] args) {
        String option = JOptionPane.showInputDialog("Enter the type of document you want to receive:");
        if ("passport".equals(option)) {
            String country = JOptionPane.showInputDialog(null, "Which country's passport would you like?");
            String name = JOptionPane.showInputDialog(null, "What is you name?");
            String countryOfOrigin = JOptionPane.showInputDialog(null, "What is you country of origin?");
            String dateOfBirth = JOptionPane.showInputDialog(null, "What is your date of birth?");
            new ChoiceAssignment().getPassport(option, country, name, countryOfOrigin, dateOfBirth);
        }
    }

    public void getPassport(String option, String country, String name, String countryOfOrigin, String dateOfBirth) {
        if ("usa".equals(country)) {
            JFrame frame = new JFrame();
            JPanel panel = new JPanel();
            JLabel label = new JLabel();
            frame.setTitle("USA Passport");
            frame.setSize(300, 400);
            frame.setVisible(true);
            frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
            label.setIcon(new ImageIcon("uspassport.jpg"));
            panel.add(label);
            frame.add(panel);
            frame.validate();
    }
}

【问题讨论】:

    标签: java image swing text label


    【解决方案1】:

    我为其设置的自定义位置或点。

    您可以将 JLabel 添加到包含您的图像的标签中。由于您想随机放置文本,因此您需要自己管理文本的大小/位置:

    JLabel text = new JLabel("Some text");
    text.setSize( label.getPreferredSize() );
    text.setLocation(...);
    label.add( text );
    

    【讨论】:

    • 您的评论毫无意义。 Swing 将使用其图标绘制标签,然后将任何子组件添加到标签中。注意我的代码使用了两个标签?如果您有问题,请使用正确的 SSCCE 来更新您的代码,以证明问题所在。对于您的问题,您需要一个 JFrame、一个带有图像的 JLabel 和一个带有文本的 JLabel。将带有文本的标签添加到带有图像的标签中,如上所示。然后将带有图像的标签添加到框架中。 SSCCE 将是大约 10-15 行代码来测试这个概念
    猜你喜欢
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    相关资源
    最近更新 更多