[英]I cant add JTextfield to JFrame on top of ImageIcon
This is my code. 这是我的代码。 Sorry for any formatting errors. 抱歉,出现任何格式错误。 Anyways, when I create my JTextField and add to the JFrame I only see my image icon, but I dont see the JTextField over it. 无论如何,当我创建JTextField并将其添加到JFrame时,我只会看到图像图标,但看不到其上方的JTextField。 What am I doing wrong? 我究竟做错了什么?
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);
}
}
Adding the components to a JPanel
and then the panel to the frame worked best for me. 将组件添加到JPanel
,然后将面板添加到框架最适合我。
like this: 像这样:
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);
}
}
I only see my image icon, but I dont see the JTextField over it. 我只看到我的图像图标,但看不到它上方的JTextField。
If you are trying to make the image a background image with the text field painted on top of the image then you can do something like: 如果您尝试将图像设置为背景图像,并且在其顶部绘制了文本字段,则可以执行以下操作:
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 );
This will only work if the text field is smaller than the image. 仅当文本字段小于图像时,这才起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.