Java – JTextfield cannot be added to JPanel in JTabbedPane

JTextfield cannot be added to JPanel in JTabbedPane… here is a solution to the problem.

JTextfield cannot be added to JPanel in JTabbedPane

I’m trying to make a basic UI using Swing. I want a JFrame with multiple tabs for JTabbedPane. If I only make 1 JPanel with JTextField it works fine, but once I want to add another JPanel and JTextField it shows nothing. What am I doing wrong here?

Here’s a simple example:

import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;

public class SwingUI {

private final JFrame frame;
    private final JTabbedPane tabbedPane;

public SwingUI(){

frame = new JFrame("Test");
        frame.setSize(1000, 1000);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new GridLayout(1, 1));

tabbedPane = new JTabbedPane();
        tabbedPane.addTab("Login", makeLoginPanel());
        tabbedPane.addTab("Login2", makeLoginPanel());  if this is left out it works
        frame.getContentPane().add(tabbedPane);

}

private JPanel makeLoginPanel(){
        JPanel p = new JPanel();
        p.setLayout(null);

JLabel lblName = new JLabel("Name:");
        lblName.setBounds(50,50,100,30);
        p.add(lblName);

JTextField x = new JTextField("text");
        x.setBounds(200,200,200,200);
        p.add(x);

return p;
    }
}

Solution

After you add components to the frame, the framework should be visible.

So:

frame.setVisible( true );

Should be the last statement in the constructor.

Also:

frame.setSize(1000, 1000);

Do not hard-code the size. You don’t know what resolution other people might be using.

Use instead:

frame.setExtendedState(JFrame.MAXIMIZED_BOTH);

The frame will open maximally on your screen.

In addition,

frame.getContentPane().setLayout(new GridLayout(1, 1));

Do not use GridLayout. The default layout is BorderLayout, which by default allows you to add a component to CENTER, and the component fills the entire space of the frame.

Related Problems and Solutions