Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find width of JTextField given no.of characters?

I have a JTextField which can accept a fixed number of characters (eg. 10 characters). I want to restrict the width of the TextField to exactly take that many characters. So given the no.of characters, is there a way to find out the width (pixels) it will take? Assume that we know the font.

like image 218
amit Avatar asked Jan 21 '23 12:01

amit


1 Answers

This will get you the exact width, though you'd want some extra pixels of padding to make it pretty.

myJTextField.getFontMetrics(myFont).stringWidth(myString);
like image 63
lins314159 Avatar answered Jan 25 '23 22:01

lins314159