如何在 JFrame 中的图像上添加文本?

How to add text over an image in a JFrame?

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

/*
 * 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();
    }
}

custom location or points that I set for it.

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

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