2

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();
    }
}
Community
  • 1
  • 1
asad_hussain
  • 1,959
  • 1
  • 17
  • 27
  • 2
    Forget about the null-layout, use [layout managers](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html) instead. But if it's a requirement, you also have to set the location and size for the textfield. (you could use `setBounds(x, y, width, height`) – Lukas Rotter Feb 05 '16 at 18:55
  • Thanks, setBounds() worked.But i have seen codes in which textfield is getting added without using setBounds().That's why i was not using setBounds(). – asad_hussain Feb 05 '16 at 19:00
  • Yes, with a proper layout manager there is no need to call `setBounds()`, but I think with a null-layout it is (or `setLocation()` & `setSize()`). – Lukas Rotter Feb 05 '16 at 19:01

2 Answers2

3

As you've been said use a proper LayoutManager for example FlowLayout:

Don't use null layout, see Why is it frowned upon to use a null layout in swing and 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();
    }
}
Community
  • 1
  • 1
Frakcool
  • 10,915
  • 9
  • 50
  • 89
3

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();
    }
}
Genti Saliu
  • 2,643
  • 4
  • 23
  • 43