我正在尝试制作一个框架并在其中添加一个文本字段。
为此,我使用了 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();
}
}
最佳答案
如果不想使用布局管理器,则需要使用 JTextField
的 setBounds(x, y, width, height)
方法设置其边界,其中 x
和 y
是文本字段在 JFrame
中的位置:
tf.setBounds(100 , 100 , 100 , 20 );
首先为框架设置布局,然后向其添加元素和组件,如完整代码所示:
import javax.swing.*;
class Tst
{
public Tst()
{
JTextField tf = new JTextField(10);
tf.setBounds(100 , 100 , 100 , 20 );
JFrame f = new JFrame();
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
f.add(tf);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String s[])
{
new Tst();
}
}
关于java - Swing 文本字段可见性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35231438/