简体   繁体   English

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

[英]How to add text over an image in a JFrame?

Hello I want to create a program that takes information and displays it over an image in a custom location or points that I set for it. 您好,我想创建一个程序来接收信息,并将其显示在自定义位置或我为其设置的点上的图像上。 I've tried different things but they do not work or display a frame. 我尝试了不同的方法,但是它们不起作用或无法显示框架。 Basically, I am wondering how to add text over the image. 基本上,我想知道如何在图像上添加文本。 Thanks! 谢谢!

/*
 * 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. 自定义位置或我为此设置的点。

You can add a JLabel to the label containing your image. 您可以将JLabel添加到包含图像的标签中。 Since you want to randomly position the text you will need to manage the size/location of the text yourself: 由于要随机放置文本,因此需要自己管理文本的大小/位置:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM