Thursday, 14 May 2015

FlowLayout in Java


This is the default Layout Manager that every panel uses unless you use the setLayout method to change it. It keeps adding components to the right of the preceding one until it runs out of space; then it starts with the next row. The code in Listing 17.27 shows how to place 30 buttons in an applet using FlowLayout.

Note
The creation of a new layout and the use of the setLayout method are superfluous in this case because the panel comes with a FlowLayout as a default. They're included here to show you how you create and define the Layout Manager for a panel.


Listing 17.27. Placing 30 buttons in an applet using FlowLayout.
import java.awt.*;
import java.applet.Applet;


public class flowlayout extends Applet{
    Button the_buttons[];

    public void init()
    {   int i;
        int n_buttons; 
        FlowLayout fl; 
        String name;

        //make a new FlowLayout manager
        fl = new FlowLayout(); 
        //tell the applet to use the FlowLayout Manager
        setLayout(fl); 
        n_buttons = 30; 
        the_buttons = new Button[n_buttons];
        //make all the buttons and add them to the applet
        for(i=0;i<n_buttons;i++) {
            name = "Button " + i;
            the_buttons[i] = new Button(name);
            add(the_buttons[i]); 
        }
    }

}

You might be wondering how this is possible. The answer is that the FlowLayout Manager follows its rule; it places elements in a row until there isn't room for more and then goes to the next, regardless of the size of the container.


No comments:

Post a Comment