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.
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);
This approach only makes sense for unproportional fonts. Otherwise you'd had to find the 'biggest' char in the charset to make the box wide enough for 10 chars of this type.
A practical approach would be to 'guess' a wide character and compute the width so you a good propability that the text field will be big enough for usual input. Adapting lins314159 example code:
myJTextField.getFontMetrics(myFont).stringWidth("wwwwwwwwww);
JTextField textField = new JTextField(10);
The UI will size the text field automatically. I believe it does in fact use a "W" as the sizing character, so it most cases it will be larger than you need. If you want the width to be exact then use a monospaced font.
精彩评论