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

时间:2015-05-23 18:34:36

标签: java image swing text label

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

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

1 个答案:

答案 0 :(得分:2)

  

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

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

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