Search code examples
javaswinguser-interfacejtextfieldevent-dispatch-thread

Nothing is displayed when I add a JTextField


Nothing is displayed if I change the code from the first example to the second (See screenshots:

Main class:

public class Main extends JTabbedPane {
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        JFrame.setDefaultLookAndFeelDecorated(true);

        JFrame f = new JFrame("Math");
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        int x = dim.getWidth() > 800 ? (int) (dim.getWidth() / 2 - 400) : 0;
        int y = dim.getWidth() > 800 ? (int) (dim.getHeight() / 2 - 300) : 0;
        f.setBounds(x, y, 800, 600);
        f.setResizable(false);
        f.setContentPane(new Main());
    }

    Main() {
        super();
        addTab("Pythagoras", new Pythagoras());
    }
}

Pythagoras (screenshot 1):

public class Pythagoras extends JPanel{

    Pythagoras() {
        super();
        setLayout(new FlowLayout());
        JTextField j = new JTextField("Hi :)");
        add(j);
    }
}

Pythagoras (screenshot 2):

public class Pythagoras extends JPanel{

    Pythagoras() {
        super();
        setLayout(new FlowLayout());
    }
}

Pythagoras (screenshot 3):

public class Pythagoras extends JPanel{

        Pythagoras() {
            super();
            setLayout(new FlowLayout());
    add( new JLabel("This works!"));
        }
    }

Screenshot 1Screenshot 2Screenshot 3


Solution

  • Always use Swing components in the event dispatch thread. The whole code of the main method should be wrapped into

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            // original code here
        }
    });
    

    This change makes everything appear as expected in my tests.

    Read http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html and http://docs.oracle.com/javase/6/docs/api/javax/swing/package-summary.html#threading

    Also, be careful that the JTextField constructor taking only a String as argument creates a text field with 0 as the number of columns.