2015-11-30 53 views
0

这是我的代码。对不起,任何格式错误。无论如何,当我创建我的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); 
} 
    } 
+0

1)调用'f.setVisible(true)'执行'f.add(text)'后。 2)你不需要'text.setVisible(true)'。 3)更改'contentPane'的布局管理器或将'f'添加到与BorderLayout.CENTER不同的东西,否则您将只能在下次看到该文本字段。 –

+1

是的LuxxMiner,并加强:默认情况下,JFrame使用BorderLayout,它只显示在中心的一个组件。创建一个'JPanel',添加标签和文本字段,然后将JPanel添加到JFrame中。你将不得不尝试面板的布局来获得你想要的位置关系。 – markspace

+0

@markspace但是OP已经改变了'JFrame'的'contentPane',从而改变了将要使用的布局管理器(它不是默认的'JLabel'没有布局管理器) – MadProgrammer

回答

1

将组件添加到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); 
} 

} 
1

我只看到我的形象的图标,但我没有看到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); 

这只会工作,如果文本字段比图像小。