Java Swing How to - Use null Layout








Question

We would like to know how to use null Layout.

Answer

//w ww . ja  va2s  .  c  om
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main extends JPanel {
  public Main() {
    super(null);
    JTextField tf = new JTextField(10);
    add(tf);
    Dimension d = tf.getPreferredSize();
    tf.setBounds(10, 20, d.width, d.height);
  }

  @Override
  public Dimension getPreferredSize() {
    return new Dimension(500, 300);
  }

  public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new Main());
    frame.pack();
    frame.setVisible(true);
  }
}