Java JTextField set preferred size based on font size
import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.FontMetrics; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; public class Main extends JFrame { public Main() { super("JButton"); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new FlowLayout()); JLabel nameLabel = new JLabel("Name:"); JTextField name = new JTextField(20); name.setFont(new Font("Arial", Font.BOLD, 20)); /*ww w . j a v a 2 s .c o m*/ FontMetrics fm = name.getFontMetrics(name.getFont()); name.setPreferredSize(new Dimension(150, fm.getHeight())); getContentPane().add(nameLabel); getContentPane().add(name); } public static void main(String[] args) { Main frame = new Main(); frame.pack(); frame.setVisible(true); } }