Not able to add JTextField to JFrame

Sam picture Sam · Mar 2, 2013 · Viewed 13k times · Source

I am not able to add JTextField to JFrame. My JFrame contains a JLabel and a JTextField . First, i have added the JLabel, and it is working. Here is the code.

private static void createandshowGUI()
     {

    JFrame frame =new JFrame("HelloSwing");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setBackground(Color.red);
    frame.setSize(200,200);

    JLabel label=new JLabel("New To Java!!");
    frame.getContentPane().add(label);
    frame.setVisible(true);
}
public static void main(String[] args) {
    createandshowGUI();}   //and it shows the output like below .

Frame having JLabel

Then i added JTextField .

    JLabel label=new JLabel("New To Java!!");
    frame.getContentPane().add(label);

   JTextField jtf=new JTextField();
   frame.getContentPane().add(jtf);

    frame.setVisible(true);

But then it shows output like this.

Frame having JLabel and JTextField

Please somebody help me on this issue.Can i add more than one component to JFrame?As i am new to Java, i am having a confusion between frame,ContentPane and Layouts.

Answer

Daniel Rikowski picture Daniel Rikowski · Mar 2, 2013

Actually you are successful in adding the JTextField. The problem you are experiencing stems from the layout manager which stretches it across the whole frame.

The content pane of JFrame uses a BorderLayout manager by default. (See How to Use BorderLayout)

In my application a always ended up using the MigLayout manager, but first you might want to familiarize yourself with layout managers in general. (See A Visual Guide to Layout Managers)