Switch (LAYOUT_MANAGERS)

     

Switch (LAYOUT_MANAGERS) {

Now we look at different ways to organize controls on your panels.

Case: FLOW LAYOUT :

This is the simplest to use, and is used in many Swing examples in this book. In part, that's because you don't have to do much to make it go, and it is used by default by Jpanels. It arranges components in a flow ”that is, by adding them in a certain direction. The effect is similar to typing into a word processor: as you add new words, they just get tacked onto the end. FlowLayout has three constructors.

  1. FlowLayout()

    Nuff said.

    There are two component orientations possible for a Flow Layout: left to right and right to left. They are

     

     ComponentOrientation.LEFT_TO_RIGHT ComponentOrientation.RIGHT_TO_LEFT 

    You specify which you want to use like this:

     

     contentPane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); 

  2. FlowLayout(int alignment)

    Three alignments can specify the orientation in the FlowLayout constructor. They are

     

     FlowLayout.LEADING (components should be left-aligned) FlowLayout.CENTER FlowLayout.TRAILING (components should be right-aligned) 

  3. public FlowLayout(int alignment, int horizontalGap, int verticalGap)

    The horizontal and vertical gap parameters allow you to specify the number of pixels to put between each component. The default gap is 5.

FlowLayoutExample.java
 

 package net.javagarage.demo.swing.layouts; import java.awt.Container; import java.awt.FlowLayout; import javax.swing.JButton; /**<p>  * Shows how to use a FlowLayout  * with an alignment and horizontal and  * vertical gaps  * between each component.  * </p>  * @author Eben Hewitt  **/ public class FlowLayoutExample { public static void main(String[] args) { BasicFrame frame = BasicFrame.getInstance(); Container pane = frame.getContentPane(); int hGap = 10; int vGap = 20; pane.setLayout(new FlowLayout(FlowLayout.RIGHT,             hGap, vGap)); pane.add(new JButton("First")); pane.add(new JButton("Second")); pane.add(new JButton("Third")); frame.pack(); frame.setVisible(true); } } 

Figure 25.2. A flow layout with the mouse hovering over the second button.

graphics/25fig02.gif


Case: BORDER LAYOUT :

Border layout resizes and arranges the components within it to fit in five different regions : PAGE_START , LINE_START , CENTER , LINE_END , and PAGE_END . If you don't specify a constant indicating the region onto which you want to place a component, it will be added to the center.

The placement of the regions looks like this:

PAGE_START

LINE_START CENTER LINE_END

PAGE_END

Components in a Border layout are layed out according to their preferred size. That means that filling each region with a JButton will allow each component to fill up the space, but adding JLabels to each region will not, as the label's preferred size is just large enough to hold its data.

BorderLayoutExample.java
 

 package net.javagarage.demo.swing.layouts; import java.awt.BorderLayout; import java.awt.Container; import javax.swing.JButton; import javax.swing.JLabel; /**  * Demonstrate using border layout.  * @author Eben Hewitt  * @see BasicFrame  **/ public class BorderLayoutExample { public static void main(String[] args) { BasicFrame frame = BasicFrame.getInstance(); Container pane = frame.getContentPane(); pane.setLayout(new BorderLayout()); pane.add(new JButton("Center"), BorderLayout.CENTER); pane.add(new JButton("North"), BorderLayout.NORTH); pane.add(new JButton("South"), BorderLayout.SOUTH); pane.add(new JButton("East"), BorderLayout.EAST); pane.add(new JButton("West"), BorderLayout.WEST); frame.pack(); frame.setVisible(true); } }//end BorderLayoutExample 

Figure 25.3. The border layout.

graphics/25fig03.gif


Case: BOX LAYOUT :

This layout manager arranges components from one of two directions: horizontally or vertically. The components in each region will not wrap, so if you resize the window, the components will stay arranged as you specified.

The BoxLayout class features only one constructor.

 

 BoxLayout(Container cont, int axis); 

You create a box layout specifying the orientation (axis) you want to use. It dictates along what kind of line your components will be layed out. You have four choices.

  1. X_AXIS : Add components horizontally, from left to right.

  2. Y_AXIS : Add components vertically, from top to bottom.

  3. LINE_AXIS : Components should be layed out according to the value of the container's ComponentOrientation property. That is, if the container's ComponentOrientation is horizontal, components are layed out horizontally.

  4. PAGE_AXIS : Components should be layed out according to the value of the container's ComponentOrientation property. If the container's orientation is horizontal, components are layed out vertically; otherwise , they are layed out horizontally, and components are layed out left to right. For vertical orientations, components are always layed out from top to bottom.

The first argument to the constructor specifies the container that you want to stick the layout to.

BoxLayoutExample.java
 

 package net.javagarage.demo.swing.layouts; import java.awt.Container; import javax.swing.BoxLayout; import javax.swing.JButton; //demos a simple box layout public class BoxLayoutExample { public static void main(String[] args) { doSimple(); } static void doSimple(){ BasicFrame frame = BasicFrame.getInstance(); Container pane = frame.getContentPane(); //when you add components, they will be //added vertically, from top to bottom pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS)); pane.add(new JButton("button 1")); pane.add(new JButton("button 2 is bigger")); pane.add(new JButton("button 3")); pane.add(new JButton("button 4")); pane.add(new JButton("button with a long name")); frame.pack(); frame.setVisible(true); } } //end of simple box layout 

Figure 25.4. A simple box layout.

graphics/25fig04.gif


Note that you can nest box layouts to achieve more sophisticated effects, and exert greater control over how your components are arranged. What follows is an example of how to do just that sort of thing.

NestedBoxLayout.java
 

 package net.javagarage.demo.swing.layouts; import java.awt.Container; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JPanel; // demos nested box layouts public class NestedBoxLayouts { public static void main(String[] args) { BasicFrame frame = BasicFrame.getInstance(); Container pane = frame.getContentPane(); //X == Horizontal pane.setLayout(new BoxLayout(pane, BoxLayout.X_AXIS)); //we're going to add two panels to the //content pane JPanel p1 = new JPanel(); JPanel p2 = new JPanel(); //so when we add the panels, they will go side //by side (horizontally) pane.add(p1); pane.add(p2); //now make each panel have its OWN box //layout panel one (the left panel) //will arrange its components vertically (Y) p1.setLayout(new BoxLayout(p1, BoxLayout.Y_AXIS)); //panel 2, the right panel, will arrange //horizontally, from left to right p2.setLayout(new BoxLayout(p2, BoxLayout.X_AXIS)); //add two buttons to the left panel //notate buttons like this: //Panel Num : Button Num p1.add(new JButton("PANEL 1:1")); p1.add(new JButton("PANEL 1:2")); //add three buttons to the right panel p2.add(new JButton("PANEL 2:1")); p2.add(new JButton("PANEL 2:2")); p2.add(new JButton("PANEL 2:3")); frame.pack(); frame.setVisible(true); } } //end NestedBoxLayout 

Figure 25.5. One box layout nested within another allows more sophistication.

graphics/25fig05.gif


Note that we have nested layouts of the same kind here to demonstrate how to do it so you get the control you need. But you don't have to nest layouts of the same type. You can nest a grid layout inside a box layout inside a flow layout if you want. It is common to nest layouts to get the functionality, flexibility, and control required.

Case: CARD LAYOUT:

A card layout treats each component in the container as a card on a stack. Just as with a deck of cards, only one card is visible at a time. As with much in Swing programming, the order of invocation matters; the first panel added to the layout is what is displayed when the frame is first shown.

The CardLayout class offers a set of methods to flip through the cards sequentially, or to show a particular card to show a panel based on its String name. This is useful in working with weezards (step-by-step panels the user must go through). Note that Swing also gives you for free the tabbed pane, which is covered next with an illustrative example in case you need that kind of specific functionality. In fact, using a tabbed pane is easier than using card layout, because a JTabbedPane implements its own layout.

Following are the steps to make this layout go:

 

 //create a panel to hold all the cards JPanel cards; final static String PANEL_ONE = "My first panel"; final static String PANEL_TWO = "My second panel"; //... //now make each card, which is just a JPanel JPanel card1 = new JPanel(); JPanel card2 = new JPanel(); //... //initialize the panel that holds the cards cards = new JPanel(new CardLayout()); //they get String names here cards.add(card1, PANEL_ONE); cards.add(card2, PANEL_TWO); //Now to show a card, you get the layout from the cards JPanel CardLayout layout = (CardLayout)(cards.getLayout()); //call the show() method and pass it the String name layout.show(cards, PANEL_TWO); 

That's all you need to do. The following methods of the CardLayout class let you choose panes:

 

 void first(Container) void next(Container) void previous(Container) void last(Container) void show(Container, String) 

Again, unless you're doing a wizard, it's generally easier to use a JTabbedPane to get the same effect.

Case: GRID LAYOUT:

Grid layout presents components within a grid. Each cell in a grid is the same size. You place one component in each cell. Components within a grid cell take up all of the available space in the cell .

There are three constructors available for creating a grid layout.

  • public GridLayout() Creates a grid with a single row, and one column for each component.

  • public GridLayout(int rows, int cols) Creates a grid with the specified number of rows and columns . Sometimes.

  • public GridLayout(int rows, int cols, int hGap, int vGap) Creates a grid with the specified number of rows and columns (sometimes), and adds space between the components.

Note that you can also set the number of rows and columns using the methods setRows() and setColumns() . However, the number of columns you specify is ignored completely if the value you specify is non-zero . Whether you use setColumns() or pass them into the constructor. In this case, the number of columns is determined by the number of components you have over the number of rows. Huh?

If I create a grid layout and create six components with five rows, I have more components than rows. So the layout will spill over, creating two columns. It then will distribute the components as evenly as possible over each column ”ignoring my request to set a certain number of columns. I wind up with two columns of five rows each, with components in each of the first three rows of both columns, and empty cells at locations (4,0), (4,1), (5,0), (5,1).

These methods will throw an IllegalArgumentException if both the rows and columns are set to 0.

Here is an example.

GridLayoutExample.java
 

 package net.javagarage.demo.swing.layouts; import java.awt.Container; import java.awt.GridLayout; import javax.swing.JButton; //demo how public class GridLayoutExample { static int rows, cols, hGap, vGap; public static void main(String[] args) { BasicFrame frame = BasicFrame.getInstance(); Container pane = frame.getContentPane(); //let's have 5sall around! rows = cols = hGap = vGap = 5; //create layout: notice how my pleas //for certain number of columns is viciously //ignored, laughed at even. pane.setLayout(new GridLayout(rows, cols, hGap, vGap)); //add components pane.add(new JButton(" one ")); pane.add(new JButton(" two ")); pane.add(new JButton(" three ")); pane.add(new JButton(" four ")); pane.add(new JButton(" five ")); pane.add(new JButton(" six ")); //we have space left over for two more //in each column because we have 10 cells: //5 rows * 2 columns frame.pack(); frame.setVisible(true); } } //end of Grid Layout example 

Notice that if you resize the window, the layout does not shift. You still have the number of columns the layout manager created.

Figure 25.6. The grid layout.

graphics/25fig06.gif


Case: GRID BAG LAYOUT:

graphics/fridge_icon.jpg

FRIDGE

You have to be careful in keeping track of your grid. If you add components into the same cell, they can overwrite each other in the display, causing one to be in front of the other. This is not only undesirable in itself, but can cause strange behavior. For example, if you resize the window, you might find the higher z-indexed component flipping in front of the other.


GridBagLayout (a.k.a. GBL) can be very tricky to work with. It is far more complex to create, manage, keep track of, and modify than other layout types. Things sort of come down to two choices in Swing apps: nest a number of other layout types within each other as necessary, or use GridBagLayout.

Now that we're scared, all a GBL does is allow the placement of components in a grid of rows and columns (so far so good, it's just like Grid Layout, we can do this, okay, what's next?), allowing components to span multiple rows and/or columns (nnnnnoooooooooo!!!!!!!).

Not all columns have to have the same width, and not all rows have to have the same height.

This is actually a lot like nested HTML tables, isn't it? It is enough like them that we'll be able to manage it. If you can write an HTML page that nests tables within tables to control your layout at a granular level, you are a lot of the way home with GBL. The problem turns out to be not so much the GBL itself, but the fact that the layout gets the size of the cells in the grid from the preferred size of the components within it. For that reason, you will likely have to do some experimenting as you work with GBL, because this changes across components. For example, a button will fill up all of the available space, whereas a label will only take what it needs bare minimum.

Constraints

The GBL specifies the size and position of each component using constraints. Constraints are objects of type GridBagConstraint. You don't need a new GridBagConstraint for each component; you can reuse a constraint if it's convenient .

When you create a constraint, you can set the following fields: gridx and gridy.

Specify the row and column at the upper left of the component, with coordinates (0,0) representing the upper-left column. X represents the horizontal plane and Y the vertical plane. You can also use the default value GridBagConstraints.RELATIVE to indicate that the component should be placed immediately to the right of or immediately below the component that was added to the container just before this component was added.

  • Gridwidth Specify the number of columns in the display. Default is 1.

  • Gridheight Specify the number of rows in the display. Default is 1.

  • Fill Used to indicate the manner in which to resize the component when the component's display area is larger than the component's requested size.

    Possible values:

    graphics/fridge_icon.jpg

    FRIDGE

    GridBagLayout allows a component to span multiple rows only when the component is in the column farthest to the left, or the component has positive gridx and gridy values.


    NONE Default.

    HORIZONTAL The component will entirely fill its display area horizontally. The height will not change.

    VERTICAL The component will entirely fill its display area vertically. The width will not change.

    BOTH The component will fill its entire display area.

  • ipadx, ipady Specifies how much padding to add to the minimum size of the component. Default is 0.

  • Insets Specifies the minimum amount of space between the component and the edges of its display area (internal padding). The value is specified as an object of type Insets. By default, components have no external padding.

  • Anchor Use to determine where to place your component when the component is smaller than its display area. Valid values are CENTER (default), PAGE_START, PAGE_END, LINE_START, LINE_END, FIRST_LINE_START, FIRST_LINE_END, LAST_LINE_END, and LAST_LINE_START .

  • weightx, weighty Use the values to specify how to distribute space among columns ( weightx ) and among rows ( weighty ) during resizing.

GridBagLayoutExample.java
 

 package net.javagarage.demo.swing.layouts; import java.awt.Container; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; //you could do this to save typing: //import static javax.swing.GridBagConstraints.*; //i don't here in order to be explicit //demos a grid bag layout public class GridBagLayoutExample { public static void main(String[] args) { doSimple(); } static void doSimple(){ //BasicFrame frame = BasicFrame.getInstance(); JFrame frame = new JFrame("My App"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container pane = frame.getContentPane(); //create the layout and constraints GridBagLayout layout = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); frame.setLayout(layout); //create all of the controls we will add JLabel lblDesc = new JLabel(" This is a description. " + "It contains some instructive text. "); JLabel lblEnter = new JLabel("Enter coolest Simpson: "); JTextField txtField1 = new JTextField(20); JButton btnSave = new JButton("save"); JButton btnCancel = new JButton("cancel"); //now create new constraints for each component //before adding it to the pane //constrain Description Label //gives height to the whole area constraints.ipady = 50; //puts space around the label constraints.ipadx = 20; layout.setConstraints(lblDesc, constraints); pane.add(lblDesc); //constrain Enter label constraints.ipady = GridBagConstraints.NONE; layout.setConstraints(lblEnter, constraints); pane.add(lblEnter); //constrain Text Field constraints.gridwidth = GridBagConstraints.CENTER; constraints.anchor = GridBagConstraints.LAST_LINE_START; layout.setConstraints(txtField1, constraints); pane.add(txtField1); //constrain Cancel Button constraints.gridx = 2; //add constraints to Cancel button layout.setConstraints(btnCancel, constraints); //add Cancel button to the pane pane.add(btnCancel); pane.add(Box.createRigidArea(new Dimension(30,0))); //constrain Save button constraints.gridx = 3; constraints.gridy = 3; layout.setConstraints(btnSave, constraints); pane.add(btnSave); frame.setSize(frame.getPreferredSize()); frame.pack(); frame.setVisible(true); } } 

Figure 25.7. The grid bag layout in action.
graphics/25fig07.gif

} //end LayoutManagers.stepInto();



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net