javaswingjformattedtextfield

How to set size of JFormattedTextField


Hello I was just wondering is it possible to set the size of a JFormattedTextField like it is with a regular JTextField for example.

Below I have a normal JTextField and am just setting it to a decent size.

 textField = new JTextField(20);//Setting the JTextFields size to 20

But say I was to have a JFormattedTextField as below how would I set the size of it I cant seem to find anything relating to it online any suggestions or help greatly appreciated.

 textField =new JFormattedTextField(new DecimalFormat("###,###"));//This JFormattedTextField is being set so only decimals may be entered into it
    

Solution

  • Since JFormattedTextField extends from JTextField, you can use all of the methods available to the parent with the child, here the setColumns(...) method which will set the value for the displayed column width of the component. This is all as per the JFormattedTextField API.

    For example:

    // in the field declaration section
    private JFormattedTextField textField = new JFormattedTextField(new DecimalFormat("###,###"));
    
    // .....
    
    // in the constructor
    textField.setColumns(20);