Java Swing How to - Create JTextField and set the length








Question

We would like to know how to create JTextField and set the length.

Answer

import java.awt.FlowLayout;
//from   w  w w. j ava 2s . co m
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main extends JFrame {
  public Main() {
    super("JTextField Test");

    getContentPane().setLayout(new FlowLayout());

    JTextField textField1 = new JTextField("1", 1);
    JTextField textField2 = new JTextField("22", 2);
    JTextField textField3 = new JTextField("333", 3);

    getContentPane().add(textField1);
    getContentPane().add(textField2);
    getContentPane().add(textField3);

    setSize(300, 170);
    setVisible(true);
  }

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