> I have a JTextField that I have set the number of
> columns to 13. However, when it is displayed, it is
> bigger that the space needed to display
> "1234567890123". Why is this? What can I do about it?
>
Try typing in WWWWWWWWWWWWW and iiiiiiiiiiii.
The width of each character in the font is not the same.
Easiest solution: make it smaller or don't worry about it. As long as the user can see all of what they are typing it should be good, right?
> In this case, I am only displaying numeric values
> ("1-9", ".", ","), I don't have to worry about
> internationalization issues, and formatting is
> important.
>
> Is there a way to adjust the preferred size to the
> max size needed for a text string like
> "255.255.255.255"?
There might be a better way. But if 13 is too long, see how 12 looks with the data. If that is still too long try 11, etc.
perhaps just creating it with the set number, then resetting the text might do
import javax.swing.*;
import java.awt.*;
class Testing
{
public void buildGUI()
{
JFrame f = new JFrame();
JTextField tf = new JTextField("255.255.255.255");
tf.setFont(new Font("monospaced",Font.PLAIN,12));
f.getContentPane().add(tf);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tf.setText("");
f.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Testing().buildGUI();
}
});
}
}
Is there a way to adjust the preferred size to the max size needed for a text string like "255.255.255.255"?
JTextField ipAddressField = createSizedTextField("000.000.000.000");
...
public static final JTextField createSizedTextField(String sizingString)
{
JTextField f = new JTextField(sizingString);
f.setPreferredSize(f.getPreferredSize());
f.setText(null);
return f;
}
It's not something I've seen before either, I've never needed to do it. But it is at least PLAF/platform/etc independent (provided all numbers are the same width - some fonts may have narrower "1" glyphs, though it would be unusual). Naturally it may break if you then reconfigure the font/border/etc on the field, but the changes required to cope with that should be fairly obvious :o)