Java Swing JFrame Layout

DanMatlin picture DanMatlin · Dec 28, 2011 · Viewed 43.2k times · Source

I just wrote a simple code where I want a textfield and a button to appear on the main frame, but after running all I see is the textfield.

If I write the code of the button after the textfield then only the button is displayed.

Any idea why?

    JFrame mainframe=new JFrame();
    mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainframe.setBounds(0,0,200,200);
    JButton jb=new JButton();
    jb.setText("Leech");
    mainframe.add(jb);
    JTextField link=new JTextField(50);
    mainframe.add(link);
    mainframe.pack();
    mainframe.setVisible(true);

Answer

Robin picture Robin · Dec 28, 2011

The default layout on a JFrame is a BorderLayout. Calling the add method on a Container with such a layout is equivalent to a call add(..., BorderLayout.CENTER). Each of the locations of the BorderLayout can contain only one element. Hence making two calls

mainframe.add(jb);
mainframe.add(link);

results in a CENTER containing the last component you added. If you want to avoid this you can either add it to different locations, or use another layout manager (for example a FlowLayout) by calling JFrame#setLayout