Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Swing : JTextField.setColumns(int) issue  RSS feed

 
Gilles Marceau
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ranchers,

i have a problem using the JTextField.setColumns(int) method: the
number of columns displayed is not the expected one. The result on
the display is always a bigger number of columns.
Do you know the reason of this strange behavior or a way to work
around this issue ?

Thanks.

Gilles
[ April 24, 2008: Message edited by: Gilles Marceau ]
 
Brian Cole
Author
Ranch Hand
Posts: 947
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Gilles Marceau:
i have a problem using the JTextField.setColumns(int) method: the
number of columns displayed is not the expected one. The result on
the display is always a bigger number of columns.
Do you know the reason of this strange behavior or a way to work
around this issue ?


The default font (in most LnFs) is a proportional-width font. Because
of this, setColumns() is not exact. Last time I checked, if you call
setColumns(6) and set the text to "mmmmmm" the field will actually
be a few pixels too short due to insets issues. [two notes: (1) 'm' is
usually a font's widest char. (2) I'm presuming the layout manager
lays out the JTextField at its preferred size.]

One way to fix a JTextField to be exactly the width of some text is
to do something like:
JTextField tf = new JTextField("some text");
tf.setPreferredSize(tf.getPreferredSize());
tf.setText("");
yourContainer.add(tf);

[ April 24, 2008: Message edited by: Brian Cole ]
 
Gilles Marceau
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for the advice, this is really helpful.

Gilles
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!