Jay
Jay

Reputation: 2454

GridBagLayout resizing components

This is what I've layed out using a GridBagLayout:

normal layout

But, when I select a file a couple of labels are supposed to be populated. This is what it looks like after I make a file selection using those small "..." buttons:

messed layout

As you can see , the entire layout gets messed up. All I am doing in the actionlistener is this:

            fileTxt = fileChooser.getSelectedFile();
            fileTxtField.setText(fileTxt.getAbsolutePath());
            labels = getLabels(); 
            lbl1.setText(labels[0].toUpperCase());
            Dimension size = lbl1.getPreferredSize();
            lbl1.setMinimumSize(size);
            lbl1.setPreferredSize(size);
            lbl2.setText(labels[1]);
            lbl2.setToolTipText(longLbl);
            size = lbl2.getPreferredSize();
            lbl2.setMinimumSize(size);
            lbl2.setPreferredSize(size);
            button1.setPreferredSize(new Dimension(20,25));
            button2.setPreferredSize(new Dimension(20,25));

So, basically, the buttons are going to their original sizes and not preferred sizes.and that messes up the entire layout. How do I fix this? All components are set not to fill with the gridbagconstraint of gridBagConstraints.fill set to GridBagConstraints.NONE - however, the layout still gets messed up :(

UPDATE

As per your suggestions, I removed the code that was calling setPreferredSize() method, and this is what I get:

enter image description here

Obviously, this is what I want to avoid - a button, that is bigger than its text, that was reason for setting setPreferredSize on the button. Now what do I do?

Upvotes: 1

Views: 4686

Answers (2)

Nitin Chhajer
Nitin Chhajer

Reputation: 2339

There is a simple solution to this. The extra width of the buttons is due to the default margins on the left and right of the button text. By default it is 14

you can set btn.setMargin(new Insets(2, 0, 2, 0)); and that extra gap will go.

Upvotes: 3

StanislavL
StanislavL

Reputation: 57381

Don't call setPreferredSize(). Let LayoutManager do this.

In your GridBagConstraints define fill and weightx parameters to define how extra space should be distributed.

Upvotes: 5

Related Questions