Layouts and Layout Managers

Chapter: Layouts and Layout Managers

The Absolute (or null) Layout lets you place whatever you want wherever you like. The end result tends to look terrible. Java comes with various layout managers that make your windows look much prettier.

Q. 2
What happens if you put FlowLayout in your Ex1 JApplet instead?


Basically, FlowLayout is one step better than AbsoluteLayout. It will try to place your components neatly, left to right,top to bottom. Here's how my applet displays:


% codebase=huckleberryhoundpackage>
% archive = "lab6.jar" width=400 height=200> 

Other layouts will do cool things. Feel free to read about them or experiment.


Exercise 2

In Eclipse, click on your package name in the package explorer and then do New > other > windowbuilder > Swing Designer > JApplet. Add a FlowLayout. Add nine JButtons with labels 1,2,...,9. If you now run your JApplet, you will probably see something like:

Now pull in a GridLayout, and you may see:

Now for the main point of this exercise. Go into the Source Tab, and you'll notice code that may look like:

                getContentPane().setLayout(new GridLayout(0, 8, 0, 0));
                
                JButton button_3 = new JButton("4");
                getContentPane().add(button_3);
                
                JButton button_5 = new JButton("6");
                getContentPane().add(button_5);
                

You will stay in the Source tab for the remainder of this exercise. Read The Java API documentation to find out what the new GridLayout(...) means. Also notice that your buttons are maybe not being added in a sensible order. Change the numbers in that new GridLayout() statement; then change your code so that the JButtons are added in the right order. (It's possible you'll need to delete some extraneous lines too.)

When done, your JApplet will run and produce




rhyspj@gwu.edu