Java Swing How to - Disable resizing of JTextField








Question

We would like to know how to disable resizing of JTextField.

Answer

import java.awt.FlowLayout;
/*  w w w .  j  av  a 2s  .co  m*/
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Main {

  public static void main(String[] args) {
    JTextField smallField = new JTextField(5);
    JTextField largeField = new JTextField(20);
    JPanel gui = new JPanel(new FlowLayout());
    gui.add(smallField);
    gui.add(largeField);
    JFrame f = new JFrame("Text Field Size");
    f.add(gui);
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    f.pack();
    f.setLocationByPlatform(true);
    f.setVisible(true);
  }
}