Reputation: 2001
I am trying to make a frame and add a text field inside it.
For that I used JTextField
. But it's not appearing.
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();
}
}
Upvotes: 2
Views: 146
Reputation: 2723
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();
}
}
Upvotes: 3
Reputation: 11153
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();
}
}
Upvotes: 3