我无法将JTextfield添加到ImageIcon顶部的JFrame中



这是我的代码。很抱歉出现任何格式错误。无论如何,当我创建我的JTextField并添加到JFrame时,我只看到我的图像图标,但我看不到上面的JTextField。我做错了什么?

package com.company;
 import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class Main extends JFrame {
public static void main(String[] args)  throws IOException {
    String path = "C:\Users\home\Pictures\Papa2.jpg";
    File file = new File(path);
    BufferedImage image = ImageIO.read(file);
    JLabel label = new JLabel(new ImageIcon(image));
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(label);
    f.pack();
    f.setLocation(200, 200);
    f.setVisible(true);
    f.setResizable(false);
    JTextField text = new JTextField(40);
    text.setVisible(true);
    f.add(text);
}
    }

将组件添加到JPanel,然后将面板添加到框架对我来说效果最好。

像这样:

public static void main(String[] args)  throws IOException {
 String path = "C:\Users\home\Pictures\Papa2.jpg";
 File file = new File(path);
 BufferedImage image = ImageIO.read(file);
 JLabel label = new JLabel(new ImageIcon(image));
 JFrame f = new JFrame();
 JTextField text = new JTextField(40);
 JPanel panel = new JPanel();
 panel.add(label);
 panel.add(text);
 f.add(panel);
 f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 f.getContentPane().add(label);
 f.pack();
 f.setLocation(200, 200);
 f.setVisible(true);
 f.setResizable(false);
 }
}

我只看到我的图像图标,但我没有看到上面的JTextField。

如果你试图使图像成为背景图像,并在图像顶部绘制文本字段,那么你可以这样做:

JLabel label = new JLabel( new ImageIcon(...) );
label.setLayout( new FlowLayout() );
JTextField textField = new JTextField(20);
label.add( textField );
JFrame frame = new JFrame();
frame.add(label, BorderLayout.CENTER);
frame.pack();
frame.setVisible( true );

只有当文本字段小于图像时,这才会起作用。

最新更新