Search code examples
javaswingsizejtextfield

JTextField only updates size when window size changes


I have set my JTextField variable to update the text when I select my checkbox using an ItemListener variable. Although the text updates, the size does not update BUT only updates when I maximize or minimize the window. Do you have any idea why this happens?

Here is my code:

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JFrame;
import javax.swing.JCheckBox;
import javax.swing.JTextField;

class Fruitbox extends JFrame
{
    private JTextField Atext;
    private final JCheckBox Abox;
    private final JCheckBox Bbox;
    private String currentString;

        public Fruitbox()
        {
            super("Hey you da best");
            setLayout(new FlowLayout());

            Atext = new JTextField("Fruit");
            Abox = new JCheckBox("Apple");
            Bbox = new JCheckBox("Banana");

            add(Abox);
            add(Bbox);
            add(Atext);

            Trigger t = new Trigger();
            Abox.addItemListener(t);
            Bbox.addItemListener(t);
        }
            class Trigger implements ItemListener
            {
                    @Override
                    public void itemStateChanged(ItemEvent e)
                    {
                    String S = "Fruit";
                    if(Abox.isSelected() && Bbox.isSelected())
                        S = "Apple and Banana";

                    else if(Abox.isSelected())
                        S = "Apple";

                    else if(Bbox.isSelected())
                        S = "Banana";

                    else
                        S = "Fruit";

                    Atext.setText(S);
                    }
            }
    }



    class MainFruit
    {
       public static void main(String[] args)
     {
        Fruitbox Fruit = new Fruitbox();
        Fruit.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Fruit.setSize(300,300);
        Fruit.setVisible(true);
     }
    }

Solution

  • You can have the JTextField change size by calling revalidate() on the container that holds the JTextField from within your listener after setting its text as this has your layout managers re-layout the held components, but better overall is to make the JTextField larger to begin with by using a constructor that helps you set its columns. i.e., change this:

    Atext = new JTextField("Fruit");
    

    to this:

    Atext = new JTextField("Fruit", 25); // or some suitable value
    

    or better still

    // avoid "magic" numbers by using constants and variables
    Atext = new JTextField("Fruit", COLUMNS);  // where COLUMNS is a constant
    

    Note that variable names by convention should start with a lower-case letter, and that by following these conventions, others will more easily understand your code.