繁体   English   中英

我无法将JTextfield添加到ImageIcon上的JFrame

[英]I cant add JTextfield to JFrame on top of ImageIcon

这是我的代码。 抱歉,出现任何格式错误。 无论如何,当我创建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 );

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

暂无
暂无

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

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