摆动文本字段可见性问题



我正在尝试制作一个框架并在其中添加一个文本字段。为此,我使用了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();
    }
}

如果你不想使用布局管理器,你需要使用 JTextFieldsetBounds(x, y, width, height) 方法来设置它的边界,其中 xy 是文本字段在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();
    }
}

正如你所说,使用适当的LayoutManager,例如FlowLayout:

不要使用空布局,请参阅为什么在 swing 中使用空布局和空布局是邪恶的

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();
    }
}

最新更新