1

I'm currently making a GUI that makes use of the FlowLayout class. Now, this class is meant to allow components be set by their prefer sized methods and I believe, isn't supposed to have priority in setting the component size. However, when I used a setSize method for a JTextField, the FlowLayout object didn't seem to recognize the change size command. But when I used the setColumn method, the FlowLayout object did respond to the change in size command.

Why is this?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Izzo
  • 4,461
  • 13
  • 45
  • 82
  • 1
    *"..by their prefer sized methods and I believe, isn't supposed to have priority in setting the component size. However, when I used a setSize method.."* The preferred size and size are different things. But avoid both of them. See [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/q/7229226/418556) for the reasons why. – Andrew Thompson Oct 20 '13 at 07:17

1 Answers1

1

FlowLayout object didn't seem to recognize the change size command. But when I used the setColumn method, the FlowLayout object did respond to the change in size command. Why is this?

Form your own question i understand that you know FlowLayout works obeying component's preferred size. However to answer your question why really JTextFeild.setColumn(int) responds: Because,

As soon as setColumn(int) is called, it invalidate() the JTextFeild component and and all parents above it to be marked as needing to be laid out.

public void setColumns(int columns) {
        int oldVal = this.columns;
        if (columns < 0) {
            throw new IllegalArgumentException("columns less than zero.");
        }
        if (columns != oldVal) {
            this.columns = columns;
            invalidate(); // invalidate if column changes
        }
    }

Then while laying out, FlowLayout calls the getPreferredSize() function of JTextFeild, which is overridden and implemented such that it returns the preferred width by adding the column width:

public Dimension getPreferredSize() {
        Dimension size = super.getPreferredSize();
        if (columns != 0) {
            Insets insets = getInsets();
            size.width = columns * getColumnWidth() +
                insets.left + insets.right;  // changing the width
        }
        return size;
    }

Guess what! I am becoming fan of source code.

Sage
  • 15,290
  • 3
  • 33
  • 38