6rchid
6rchid

Reputation: 1292

Cannot resize JTextField and JScrollPane in GridBagLayout

I want to reduce the width and height of both the JTextField and JScrollPane in a GridBagLayout, but seems like the width is only reducible to the length of the longest content from the JList, by setting the text field columns. I'm not sure if I need to adjust both or just one of the sizes of the components to match the width.

I've tried setPreferredSize(), setSize(), and setting the column length on the text field but they don't seem to do anything.

enter image description here

    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 0;
    fontDialog.add(fontLabel, c);
    c.gridx = 1;
    fontDialog.add(styleLabel,c);
    c.gridx = 2;
    fontDialog.add(sizeLabel, c);
    c.gridx = 0;
    c.gridy = 1;
    fontDialog.add(fontTextField, c);
    c.gridx = 1;
    fontDialog.add(styleTextField, c);
    c.gridx = 2;
    fontDialog.add(sizeTextField, c);
    c.gridx = 0;
    c.gridy = 2;
    fontDialog.add(new JScrollPane(fontList), c);
    c.gridx = 1;
    fontDialog.add(new JScrollPane(styleList), c);
    c.gridx = 2;
    fontDialog.add(new JScrollPane(sizeList), c);
    fontDialog.pack();

Upvotes: 0

Views: 413

Answers (2)

camickr
camickr

Reputation: 324118

Components are displayed at their preferred size when added to a cell in the GridBagLayout.

c.fill = GridBagConstraints.HORIZONTAL;

You are using horizontal fill which tells the layout to fill the width of all the components to the largest width in the column, therefore overriding the preferred size.

If you don't want the text fields to increase in width, then get rid of that constraint.

Then when you create the text field you use:

JTextField textField = new JTextField(10);

The number will allow the text field to determine its own preferred size to hold 10 "W" characters.

Upvotes: 1

user9435915
user9435915

Reputation:

you have to set the minimum and the preferred size of the column in order to control the the size. Override them to be what you want.

Upvotes: 0

Related Questions