Java Swing How to - Set FlowLayout for JFrame








Question

We would like to know how to set FlowLayout for JFrame.

Answer

import java.awt.Container;
import java.awt.FlowLayout;
/* w w  w. j  a  v a 2s  .  c om*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main {
  JFrame f = new JFrame();
  Container c;
  JButton btn;
  JTextField tf;

  public Main() {
    f.setBounds(50, 50, 300, 300);

    c = f.getContentPane();
    c.setLayout(new FlowLayout());

    btn = new JButton("OK");
    tf = new JTextField(20);

    c.add(btn);
    c.add(tf);

    f.setVisible(true);
    f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
  }

  public static void main(String[] val) {
    new Main();
  }
}