这是我的代码。对不起,任何格式错误。无论如何,当我创建我的JTextField并添加到JFrame中时,我只能看到我的图像图标,但我没有看到它的JTextField。我究竟做错了什么?我无法将JTextfield添加到ImageIcon顶部的JFrame上
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);
}
}
1)调用'f.setVisible(true)'执行'f.add(text)'后。 2)你不需要'text.setVisible(true)'。 3)更改'contentPane'的布局管理器或将'f'添加到与BorderLayout.CENTER不同的东西,否则您将只能在下次看到该文本字段。 –
是的LuxxMiner,并加强:默认情况下,JFrame使用BorderLayout,它只显示在中心的一个组件。创建一个'JPanel',添加标签和文本字段,然后将JPanel添加到JFrame中。你将不得不尝试面板的布局来获得你想要的位置关系。 – markspace
@markspace但是OP已经改变了'JFrame'的'contentPane',从而改变了将要使用的布局管理器(它不是默认的'JLabel'没有布局管理器) – MadProgrammer