Search code examples
javaswinguser-interface

JTextField randomly not appearing in program even when code is not changed


I'm trying to write a small UI program with Swing. I need to have a few textfields, but defining a new textfield or textarea (I don't even have to add it to a Frame) will randomly prevent themselves and anything that is added after them in the code from appearing onscreen.

I can recompile the same code without making any changes and maybe 1/3 of the time it will work properly. What's causing this problem and is there any way I can change it?

import java.awt.*;
import javax.swing.*;

public class ThisApp
{
    public static void main(String [] Args)
    {
        new ThisUI();       
    }
}


class ThisUI extends JFrame //implements ActionListener
{
    public ThisUI()
    {
        setTitle("ThisApp - Best in the business");
        setResizable(false);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(300, 200);
        setLayout(new GridLayout(2,1));

        JButton cat = new JButton("Cat");

        this.add(new JButton("Button"));
        this.add(new JTextField("CAT CAT",10));     
    }
}

Solution

  • The problem is you add components to the frame AFTER the frame is visible and don't invoke the layout manager so all the components have a size of 0 so there is nothing to paint.

    The frame must be made visible AFTER all the components have been added to the frame.

    So the structure of your code should be something like:

    setTitle("ThisApp - Best in the business");
    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    setLayout(new GridLayout(2,1));
    
    JButton cat = new JButton("Cat");
    this.add(new JButton("Button"));
    this.add(new JTextField("CAT CAT",10));     
    
    setSize(300, 200);
    setLocationRelativeTo( null );
    setVisible(true);