我正在尝试制作一个框架并在其中添加一个文本字段。
为此,我使用了JTextField
。但它没有出现。
import java.awt.*;
import javax.swing.*;
class Tst
{
JFrame f;
JTextField tf;
public Tst()
{
f=new JFrame();
tf=new JTextField(10);
f.setSize(400,400);
f.add(tf);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String s[])
{
new Tst();
}
}
答案 0 :(得分:3)
正如您所说,使用适当的LayoutManager例如FlowLayout:
请勿使用空布局,请参阅Why is it frowned upon to use a null layout in swing和Null layout is Evil
import java.awt.*;
import javax.swing.*;
class Tst {
JFrame f;
JTextField tf;
public Tst() {
f=new JFrame();
tf=new JTextField(10);
f.setLayout(new FlowLayout()); //Add a proper layout BEFORE adding elements to it. (Even if you need it to be null (Which I don't recommend) you need to write it here).
f.add(tf);
f.pack(); //Use pack(); so Swing can render the size of your window to it's preferred size
//f.setSize(400, 400); //If you really need to set a window size, do it here
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Don't forget this line.
}
public static void main(String s[]) {
new Tst();
}
}
答案 1 :(得分:3)
如果您不想使用布局管理器,则需要使用JTextField
的{{1}}方法设置其边界,其中setBounds(x, y, width, height)
和x
位置y
中的文本字段:
JFrame
首先将布局设置到您的框架,然后向其中添加元素和组件,如完整代码:
tf.setBounds(100 , 100 , 100 , 20 );