Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java unreasonable jtextfield sizing issue

I have searched all problems like this but I couldn't find the solution.

public class FormPanel extends JPanel
{
    private JLabel namelabel;
    private JLabel occlabel;
    private JTextField nametext;
    private JTextField occtext;
    private JButton okButton;

    public FormPanel() {
        Dimension dim = getPreferredSize();
        dim.width = 250;
        setPreferredSize(dim);
        namelabel = new JLabel("Name : ");
        occlabel = new JLabel("Occupation : ");
        nametext = new JTextField();
        nametext.setPreferredSize(new Dimension(80,20));
        occtext = new JTextField();
        occtext.setColumns(20);
        okButton = new JButton("OK");

        Border inner = BorderFactory.createTitledBorder("Add Person : ");
        Border outer = BorderFactory.createEmptyBorder(5,5,5,5);

        setBorder(BorderFactory.createCompoundBorder(inner,outer));
        setLayout(new GridBagLayout());
        GridBagConstraints gc = new GridBagConstraints();
        gc.gridx = 0;
        gc.gridy = 0;
        gc.weightx = 1;
        gc.weighty = 1;
        gc.fill = GridBagConstraints.NONE;

        add(namelabel,gc);
        gc.gridx = 1;
        gc.gridy = 0;
        add(nametext,gc);

        gc.gridy = 1;
        gc.gridx = 0;
        add(occlabel,gc);

        gc.gridy = 1;
        gc.gridx = 1;
        add(occtext,gc);

        gc.gridy = 2;
        gc.gridx = 1;
        add(okButton,gc);

    }
}

nametext and occtext are extremely small. I tried new JTextField(20) , and string version, I tried setPreferredSize as above class, and also I tried setColumn but none of them works.

like image 326
Vivian Maya Avatar asked Dec 15 '14 02:12

Vivian Maya


1 Answers

Get rid of setPreferredSize(dim);. Let the GUI size itself via calling pack() on the top-level Window and your problem will likely go away. You're constraining the size of the container likely to smaller than is best for it, and by doing so, the GridBagLayout will then shrink its components, including your JTextFields, in a bad way.

like image 154
Hovercraft Full Of Eels Avatar answered Oct 19 '22 23:10

Hovercraft Full Of Eels