Search code examples
javaswingjtextfieldlayout-managernull-layout-manager

Swing text field visibility issue


I am trying to make a frame and add a text field inside it. For that I used JTextField. But it's not appearing.

Code

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

Solution

  • If you don't want to use a layout manager, you need to set its bounds using JTextField's setBounds(x, y, width, height) method, where x and y are position of the textfield in the JFrame:

    tf.setBounds(100 , 100 , 100 , 20 );
    

    First set layout to your frame, then add elements and components to it, like in the full code:

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