Scrigroup - Documente si articole

Username / Parola inexistente      

Home Documente Upload Resurse Alte limbi doc  


AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows
WordXml

AspAutocadCDot netExcelFox proHtmlJava
LinuxMathcadPhotoshopPhpSqlVisual studioWindowsXml

Windowing Components And Layout Classes

java

+ Font mai mare | - Font mai mic



DOCUMENTE SIMILARE

Trimite pe Messenger
Date And Advanced Classes
Data Structures And Random Number Generation
AWT Image Processing
Handling Text, Dialogs, And Lists
Color, Font, Images, And Shapes
The Component Class
Applets And Graphics
Handling URLs And Networking Exceptions
Toolkit, Window, Container, And Events
Choice, Menus, And Checkboxes


Windowing Components And Layout Classes

Building a graphical user interface for an application is an interesting and challenging task. Every graphical user interface requires components that perform specialized tasks, such as buttons that invoke actions and data entry areas for users to type in information. Components also need to be logically grouped. Javaís Abstract Windowing Toolkit (AWT) provides a rich set of ready-to-use user interface components that application developers can incorporate into their programs.




This chapter describes the application programming interface of some of the ready-made GUI components that the Java toolkit provides. It also introduces the concepts involved in laying out components on the screen using Javaís layout managers. It explains how to use the Java layout managers and how to implement custom layout managers. Throughout, detailed explanations of the methods are supplemented with examples that will assist you in building an attractive GUI. The project, at the end of this chapter, lays out some of the components described in this chapter using layout managers and demonstrates the capabilities of each of Javaís layout managers.

Windowing Components

As a developer of GUIs, you will use Javaís GUI components a lot. Some of them, such as Button, Canvas, Frame, Panel, Label, and Scrollbar are common user-interface components that nearly all GUI toolkits provide. Some classes, such as Dimension and Insets, are helper classes that embody abstractions that help make programming in a graphical environment easy. Figure 4-1 shows several components of a GUI.


Figure 4-1  Components of a graphical user interface

Layouts

All the GUI components in the Java AWT are implemented with subclasses of the Component class. As you may recall from Chapter 3, the Container is a special type of component that can contain other components. How does one arrange the Components within a container? This is where the layout manager plays a role. A layout manager is a Java object that knows how to position and size or resize components within a container that appears on the screen. Java provides a number of layout managers, each of which lays out components differently. Every container has a default layout manager that you can easily replace with another one. You can also specify absolute positions (for components) instead of using a layout manager.

Layout managers must implement the methods of the LayoutManager interface. Since all layout managers implement the same interface, if you know how to use one layout manager, then switching to a different one is easy. Applications do not invoke the methods of the LayoutManager interface directly. The Container methods add, remove, removeAll, layout, preferredSize, and minimumSize result in calls to the corresponding methods of the layout manager associated with that Container object. The layout managers that Javaís AWT provides are FlowLayout, GridLayout, BorderLayout, CardLayout, and GridBagLayout. Figure 4-2 shows two examples of what you can do with these layout managers.


Figure 4-2  Examples of BorderLayout and GridBagLayout

Summary of Windowing Component and Layout Classes

Table 4-1 summarizes Javaís Windowing Component classes. Javaís layout interfaces and classes are summarized in Table 4-2.

Table 4-1 Windowing class descriptions


Class

Description


Button

A class that implements a button, that can be pressed to invoke a user-defined action/sequence of actions.

Canvas

This class implements a generic canvas that drawing operations can be performed on, using the specified graphics device for the target device.

Dimension

The Dimension class encapsulates the height and width measurement of a component.

Frame

A class that represents a top-level window, which can function as a container for other components.

Insets

A class that specifies an inset from within a rectangular area.

Label

This class implements a graphical component, that displays a single line of noneditable text.

Panel

A class that implements a generic container in which other components can be laid out.

Scrollbar

A class that represents a scrollbar.

Table 4-2 Layout class and interface descriptions


Class/Interface

Description


LayoutManager

This defines an interface that all layout managers must implement in order to be used for laying out Components.

FlowLayout

This is a very simple layout manager that lays out components in rows, and is the default layout manager for all Panels.

GridLayout

This class implements a layout manager that lays out Components in a grid with a specified number of rows and columns and resizing the Components so that they are all of equal size.

BorderLayout

This is the default layout manager for all Windows and configures the layout of the container, using areas named North, South, East, West, and Center.

CardLayout

A layout manager for a Container that arranges its Components into cards and stacks the cards, so that only one card is visible at any time.

GridBagConstraints

This class specifies the constraints for laying out components using the GridBagLayout manager.

GridBagLayout

A very flexible layout manager that lays out components, aligning them vertically and horizontally. A set of constraints specifies how each Component is laid out within its display area.

Button

Purpose

This class represents an on-screen button.

Syntax

public class Button extends Component

Description

This class implements a button that can be pressed to invoke a user-defined action or sequence of actions. Methods of the Component class can be used with Button objects. Refer to the Event class, described in Chapter 3, to find out more about handling button related events. Figure 4-3 shows the inheritance hierarchy for the Button class.

PackageName

java.awt

Imports

import java.awt.Button;

Constructors

public Button()
public Button(String label)

Parameters

label

The text string to display on the button

Example

The following sample code shows how to construct Button objects.

import java.awt.*;

public class TestButton extends Frame

public static void main(String args[])


Figure 4-3  Inheritance hierarchy for the Button class

addNotify()

ClassName

Button

Purpose

This method creates a peer object for this Button object.

Syntax

public synchronized void addNotify()

Parameters

None.

Description

This method creates a peer for this Button. The peer allows the programmer to change the look of the button without affecting its functionality. The addNotify method is the earliest stage, in the creation of a component, that platform specific resources (such as color, fonts, and fontmetrics) may be determined. Classes that override this method must first call super.addNotify() before doing any other processing in this method.

Imports

import java.awt.Button;

Returns

None.

See Also

The ButtonPeer interface

Example

Refer to the example listed in the addNotify method of the Canvas class in this chapter and also to the section on ButtonPeer interfaces in Chapter 9.

getLabel()

ClassName

Button

Purpose

To retrieve the text string displayed on the button.

Syntax

public String getLabel()

Parameters

None.

Description

This method retrieves the text label displayed on the button.

Imports

import java.awt.Button;

Returns

The return type of this method is String. This return value contains the text string displayed on the Button object.

See Also

The setLabel method

Example

The following example demonstrates the use of this method in an application.

import java.awt.*;

public class TestButton extends Frame

public static void main(String args[])

paramString()

ClassName

Button

Purpose

To represent the parameters of this Button as a String object.

Syntax

protected String paramString()

Parameters

None.

Description

This method represents the various parameters associated with the Button as a String and returns the string. Classes that extend the Button class can override this method to add additional parameter information to the String representation. This protected method cannot be invoked from an application, but is invoked by the toString method of the Component class.

Imports

import java.awt.Button;

Returns

The return type of this method is String. This return value contains the text label of the Button object, in addition to the parameter values of the base class, Component.

See Also

The toString and paramString methods of the Component class.

Example

The following example demonstrates the use of this method in an application.

import java.awt.*;

public class TestButton extends Frame

public static void main(String args[])

setLabel(String)

ClassName

Button

Purpose

To set the label on the button to the specified string.

Syntax

public void setLabel(String label)

Parameters

label

The text string for the Button label.

Description

This method changes the text label, that is displayed on button, to the specified string.

Imports

import java.awt.Button;

Returns

None.

See Also

The getLabel method

Example

The following code illustrates the use of this method in setting the label of a button.

import java.awt.*;

public class TestButton extends Frame

public static void main(String args[])

Canvas

Purpose

A generic canvas type on which graphics operations such as drawing can be performed.

Syntax

public class Canvas extends Component

Description

This class implements a generic canvas type, on which drawing operations can be performed using the specified graphics device. Classes that extend the Canvas class must override the minimumSize method, as the default size of a Canvas is zero. Figure 4-4 shows the inheritance hierarchy for the Canvas class.

PackageName

java.awt

Imports

import java.awt.Canvas;

Constructors

public Canvas()

Parameters

None.

Example

The following sample code shows how to construct Canvas objects.

import java.awt.*;

public class TestCanvas extends Frame

public static void main(String args[])


Figure 4-4  Inheritance hierarchy for the Canvas class

addNotify()

ClassName

Canvas

Purpose

To create a peer object for this Canvas object.

Syntax

public synchronized void addNotify()

Parameters

None.

Description

This method creates a peer for this Canvas object that enables you to change the appearance of the canvas without changing the functionality of the Canvas object. The addNotify method is the earliest stage in the creation of a component where platform specific resources (such as color, fonts, and fontmetrics) may be determined. Classes that override this method must first call super.addNotify() before doing any other processing in this method.

Imports

import java.awt.Canvas;

Returns

None.

See Also

The interface CanvasPeer

Example

The following code illustrates the use of this method. The ColorCanvas class initializes the font type and the text color in the addNotify method and uses these values while painting the Canvas.

import java.awt.*;
class ColorCanvas extends Canvas

public void addNotify()

public void paint(Graphics g)


public class TestCanvas extends Frame

public static void main(String args[])

paint(Graphics)

ClassName

Canvas

Purpose

To paint the Canvas object.

Syntax

public void paint(Graphics g)

Parameters

g

The graphics context object.

Description

This method is invoked to paint the canvas object. Classes that extend the Canvas class can customize the appearance of the canvas by overriding this method.

Imports

import java.awt.Canvas;

Returns

None.

See Also

The Component and Graphics classes

Example

This sample source code implements a custom canvas type that has horizontal lines, just like a ruled sheet of paper.

import java.awt.*;

public class TestCanvas extends Frame

public static void main(String args[])


// This class implements a ruled canvas type
class RuledCanvas extends Canvas
}

Dimension

Purpose

A class that represents a height and a width measurement.

Syntax

public class Dimension extends Object

Description

The Dimension class encapsulates the height and width measurement of a component. The width and height variables of a Dimension object are public and, hence, can be accessed directly. Figure 4-5 shows the inheritance hierarchy for the Dimension class.

PackageName

java.awt

Imports

import import java.awt.Dimension;

Constructors

public Dimension()
public Dimension(Dimension d)
public Dimension(int width, int height)

Parameters

d

The source Dimension object from which to copy.

width

The width measurement of the dimension.

height

The height measurement of the dimension.

Example

This code illustrates the different ways of constructing Dimension objects.

import java.awt.Dimension;

public class DimensionTest


Figure 4-5  Inheritance hierarchy for the Dimension class

toString()

ClassName

Dimension

Purpose

To represent the parameter values of the Dimension object as a String.

Syntax

public String toString()

Parameters

None.

Description

This method returns, as a string, the values of the width and height measurements of this Dimension object prefixed by its classname (java.awt.Dimension).

Imports

import java.awt.Dimension;

Returns

None.

See Also

The toString method of the Object class

Example

import java.awt.Dimension;

public class DimensionTest

When this example is compiled and executed, the following string is printed on the screen.

d.toString() = java.awt.Dimension[width=,height=200]

Frame

Purpose

A class that represents a top-level window that can function as a container for other components.

Syntax

public class Frame extends Window implements MenuContainer

Description

This class implements a window with a title bar and border that can contain a menu bar, as well as other AWT Components. Frames and Panels are commonly used as the top-level window GUIs. Most of the functionality for this class is implemented in the Window, Container, and Component classes. Refer to those classes in Chapter 2 and Chapter 3 to get a complete picture of what you can do with Frame objects. The default layout manager for Frame window objects is BorderLayout. Figure 4-6 shows the inheritance hierarchy for the Frame class.

PackageName

java.awt

Imports

import java.awt.Frame;

Constructors

public Frame()
public Frame(String title)

Parameters

title

The string to display in the title bar of the Frame window.

Example

This example demonstrates Frame construction.

import java.awt.*;

public class FrameTest


Figure 4-6  Inheritance hierarchy for the Frame class

addNotify()

ClassName

Frame

Purpose

Creates a peer object for this Frame object.

Syntax

public synchronized void addNotify()

Parameters

None.

Description

This method creates a peer for this Frame object that enables you to change the appearance of the frame window without changing its functionality. The addNotify method is the earliest stage, in the creation of a component, that platform specific resources (such as color, fonts, and fontmetrics) may be determined. Classes that override this method must first call super.addNotify() before doing any other processing in this method.

Imports

import java.awt.Frame;

Returns

None.

See Also

The FramePeer interface

Example

Refer to the example listed in the addNotify method of the Canvas class in this chapter and also to the section on FramePeer interfaces in Chapter 9.

dispose()

ClassName

Frame

Purpose

To release all the resources that are being used by this Frame object.

Syntax

public synchronized void dispose()

Parameters

None.

Description

This method is called to release the resources of a Frame object that is no longer required.

Imports

import java.awt.Frame;

Returns

None.

See Also

The Window class

Example

Refer to the corresponding method in the Window class description in Chapter 3.

getCursorType()

ClassName

Frame

Purpose

To get the integer constant that represents the cursor type associated with this Frame object.

Syntax

public int getCursorType()

Parameters

None.

Description

This method gets the integer type, associated with the cursor for this Frame. A list of cursor types is given in the description of the setCursor method for this class.

Imports

import java.awt.Frame;

Returns

The cursor type, associated with this Frame window, is returned as an integer value and will be one of the values detailed in the list of cursor types.

Example

This example prints the integer value of the default cursor image.

import java.awt.*;

public class FrameTest

getIconImage()

ClassName

Frame

Purpose

To get the image of the icon of this Frame object.

Syntax

public Image getIconImage()

Parameters

None.

Description

This method gets the image that is displayed when the Frame is iconized.

Imports

import java.awt.Frame;

Returns

This method returns an Image object that represents the icon image used for this Frame object. Refer to the section on Image objects in Chapter 8 for more information.

See Also

The Image class

Example

The following example demonstrates the use of this method in an application.

import java.awt.*;

public class FrameTest
// this method is invoked to modify the icon being displayed for this
image
protected void modifyIcon(Frame f)

getMenuBar()

ClassName

Frame

Purpose

To get the menu bar object associated with this Frame object.

Syntax

public MenuBar getMenuBar()

Parameters

None.

Description

This method gets the MenuBar object that represents the menu bar associated with this Frame.

Imports

import java.awt.Frame;

Returns

The menu bar information, associated with this Frame window, is returned as a MenuBar object. Refer to the section on MenuBar objects in Chapter 6 for more information.

See Also

The MenuBar class

Example

The portion of code given here uses this method.

import java.awt.*;

public class FrameTest
// this method is invoked to modify the menu
protected void modifyIcon(Frame f)

getTitle()

ClassName

Frame

Purpose

To get the text string on the title bar of the frame.

Syntax

public String getTitle()

Parameters

None.

Description

This method gets the text label displayed in the title bar of the Frame window.

Imports

import java.awt.Frame;

Returns

This method returns a String object that contains the title of the Frame window as a text string.

Example

This example prints the title of the Frame window on the standard output device.

import java.awt.*;

public class FrameTest

isResizable()

ClassName

Frame

Purpose

Indicates whether this Frame window object is resizable or not.

Syntax

public boolean isResizable()

Parameters

None.

Description

This method is used to test whether or not the dimensions of this Frame object can be changed.

Imports

import java.awt.Frame;

Returns

If the Frame object is resizable, then the return value is true; otherwise this method returns false.

Example

The following code illustrates the use of this function in determining whether a Frame object is resizable or not.

import java.awt.*;
public class FrameTest

paramString()

ClassName

Frame

Purpose

To return the parameter values associated with this Frame object

Syntax

protected String paramString()

Parameters

None.

Description

The parameter values for this Frame object are returned as a String. This protected method cannot be invoked directly. The toString method of the Component superclass invokes this method.

Imports

import java.awt.Frame;

Returns

A String containing the parameter values for this Frame object.

See Also

The toString and paramString methods of the Component class

Example

The following example prints the parameter information for a Frame window object.

import java.awt.*;

public class FrameTest

When this example is compiled and executed, the following string is printed on the screen.

f.toString() = java.awt.Frame[0,0,0x0,invalid,hidden,
layout=java.awt.BorderLayout,resizable,title=Testing Frame.paramString()]

remove(MenuComponent)

ClassName

Frame

Purpose

To remove the specified menu bar object from the Frame window.

Syntax

public synchronized void remove(MenuComponent m)

Parameters

m

The MenuComponent object to be removed from this Frame.

Description

This method removes the specified menu bar from this Frame window.

Imports

import java.awt.Frame;

Returns

None.

See Also

The MenuComponent and MenuBar classes

Example

This function removes the menu bar from the specified Frame window.

import java.awt.*;

class FrameTest

setCursor(int)

ClassName

Frame

Purpose

To set the cursor to display when the pointer is within this Frame window.

Syntax

public void setCursor(int cursorType)

Parameters

cursorType

An integer constant that indicates the type of cursor to display within this Frame window. The cursor types defined in this class are

CROSSHAIR_CURSOR

Cursor image is a crosshair

DEFAULT_CURSOR

Default cursor image(arrow cursor)

E_RESIZE_CURSOR

Cursor image when the window is being resized to the right

HAND_CURSOR

The image for the cursor is a small hand

MOVE_CURSOR

The cursor image when the window is being moved

N_RESIZE_CURSOR

Cursor image when the window is being resized upwards

NE_RESIZE_CURSOR

Cursor image when the window is being resized by dragging its north-east corner

NW_RESIZE_CURSOR

Cursor image when the window is being resized by dragging its north-west corner

S_RESIZE_CURSOR

Cursor image when the window is being resized downwards

SE_RESIZE_CURSOR

Cursor image when the window is being resized by dragging its south-east corner

SW_RESIZE_CURSOR

Cursor image when the window is being resized by dragging its south-west corner

TEXT_CURSOR

Cursor image when the cursor is in an editable text window

W_RESIZE_CURSOR

Cursor image when the window is being resized to the left

WAIT_CURSOR

Hourglass cursor image

Description

This method specifies the cursor image to display when the pointer is within this Frame window. The cursor can be any one of the types listed in the Parameters section of this method.

Imports

import java.awt.Frame;

Returns

None.

Example

This code causes the cursor image to change to an image of a hand when the mouse pointer is inside the Frame window,.

import java.awt.*;

public class FrameTest

setIconImage(Image)

ClassName

Frame

Purpose

To set the image of the icon of this Frame object.

Syntax

public void setIconImage(Image image)

Parameters

image

The image to be used for the icon.

Description

This method specifies the image to use when the Frame is iconized. Some platforms do not support icons for windows.

Imports

import java.awt.Frame;

Returns

None.

See Also

The Image class

Example

The following example demonstrates the use of this method in an application.

import java.awt.*;

public class FrameTest

setResizable(boolean)

ClassName

Frame

Purpose

To enable/disable the resizable feature on this Frame object.

Syntax

public void setResizable(boolean resizable)

Parameters

resizable

A boolean value that represents whether or not the Frame window is resizable. If set to true, the Frame object is resizable; if set to false, the Frame window is not resizable.

Description

This method is used to set whether the Frame window is resizable or not.

Imports

import java.awt.Frame;

Returns

None.

Example

The following function toggles the resizable flag of the specified Frame object.

import java.awt.*;

public class FrameTest

setTitle(String)



ClassName

Frame

Purpose

Sets the text string on the title bar of the frame.

Syntax

public void setTitle(String title)

Parameters

title

The text string to display in the title bar of this Frame.

Description

This method sets the text label displayed in the title bar of the Frame window to the specified string.

Imports

import java.awt.Frame;

Returns

None.

Example

This method is used in the following example to set the title of a Frame window.

import java.awt.*;

public class FrameTest

Insets

Purpose

Specifies an inset from within a rectangular area.

Syntax

public class Inset extends Object implements Cloneable

Description

This class represents the top, left, bottom, and right insets. This class is used to calculate the actual area that may be used inside a rectangular region, after subtracting the inset on each side of the region. This class is used by layout managers to lay out components. Figure 4-7 shows the inheritance hierarchy for the Insets class.

PackageName

java.awt

Imports

import java.awt.Insets;

Constructors

public Insets(int top, int left, int bottom, int right)

Parameters

top

The distance set in from the top of the Container.

left

The distance set in from the left of the Container.

bottom

The distance set in from the bottom of the Container.

right

The distance set in from the right of the Container.

Example

This code shows how to construct an Insets object.

import java.awt.Insets;

public class InsetsTest


Figure 4-7  Inheritance hierarchy for the Insets class

clone()

ClassName

Insets

Purpose

To create a duplicate of this Insets object

Syntax

public Object clone()

Parameters

None.

Description

Creates a new instance of an Insets object and makes an exact duplicate of this Insets object.

Imports

import java.awt.Insets;

Returns

The return value is an Object that is a clone of this Insets object. You must cast this return value as an Insets object in order to use it as one.

See Also

The clone method of the Object class; the Cloneable interface

Example

import java.awt.Insets;

public class InsetsTest

toString()

ClassName

Insets

Purpose

To store the Insets objectís parameter values in a String.

Syntax

public String toString()

Parameters

None.

Description

The values of the top, left, bottom, and right insets are returned as a String object.

Imports

import java.awt.Insets;

Returns

The return value is a String that contains the values of the parameters for the Insets object. The values are prefixed by a short textual description of the property they denote.

See Also

The Object class

Example

This method is implemented in the following example.

import java.awt.Insets;

public class InsetsTest

When this example is compiled and executed, the following string is printed on the screen

i.toString() = java.awt.Insets[top=5,left=10,bottom=5,right=10]

Label

Purpose

A class that represents a single line text label.

Syntax

public class Label extends Component

Description

This class implements a graphical object that displays a single line of non-editable text. The alignment of the text can be specified. By default, label text is centered within the label. The methods of the Component class can be applied to this class. Figure 4-8 shows the inheritance hierarchy for the Label class.

PackageName

java.awt

Imports

import java.awt.Label;

Constructors

public Label()

public Label(String label)

public Label(String label, int alignment)

Parameters

label

The text string to display in the label.

alignment

The alignment mode for the text stringís position in the label.

Example

The following example demonstrates the construction of Label objects.

import java.awt.*;

public class LabelTest extends Frame

public static void main(String args[])


Figure 4-8  Inheritance hierarchy for the Label class

addNotify()

ClassName

Label

Purpose

To create a peer object for this Label object.

Syntax

public synchronized void addNotify()

Parameters

None.

Description

This method creates a peer for this Label object, which you can use to change the appearance of the label without changing its functionality. The addNotify method is the earliest stage in the creation of a component where platform specific resources (such as color, fonts, and fontmetrics) may be determined. Classes that override this method must first call super.addNotify() before doing any other processing in this method.

Imports

import java.awt.Label;

Returns

None.

See Also

The LabelPeer interface; the Component class

Example

Refer to the example listed in the addNotify method of the Canvas class in this chapter, and also to the section on LabelPeer interfaces in Chapter 9.

getAlignment()

ClassName

Label

Purpose

To get the alignment mode of the text string displayed on the label.

Syntax

public int getAlignment()

Parameters

None.

Description

This method gets the current alignment of the text displayed on the label. The mode can be one of Label.RIGHT, Label.CENTER, or Label.LEFT.

Imports

import java.awt.Label;

Returns

This method returns an integer that specifies the alignment of the label.

Example

The following example uses this method to determine a labelís alignment.

import java.awt.*;

public class LabelTest extends Frame

resize(150, 100);
show();
}

public static void main(String args[])

getText()

ClassName

Label

Purpose

To get the text string of this Label object.

Syntax

public String getText()

Parameters

None.

Description

This method gets the text string displayed on the label.

Imports

import java.awt.Label;

Returns

This method returns a String object that contains the text string displayed on the Label.

See Also

The setText method

Example

The following example demonstrates the use of this method in an application.

import java.awt.*;

public class LabelTest extends Frame

public static void main(String args[])

paramString()

ClassName

Label

Purpose

To return the parameter string associated with this Label object.

Syntax

protected String paramString()

Parameters

None.

Description

This method returns the parameter values associated with the label (such as x, y coordinates, label text, and so on) as a String object. This protected method cannot be invoked from an application, but is invoked by the toString method of the Component class.

Imports

import java.awt.Label;

Returns

The return value is a String that contains the values of the parameters for the Label object. The values are prefixed by a short textual description of the property they denote.

See Also

The toString and paramString methods of the Component class

Example

This example prints the parameter values of a label.

import java.awt.*;

public class LabelTest extends Frame

public static void main(String args[])

setAlignment(int)

ClassName

Label

Purpose

To set the alignment of the text string on the label.

Syntax

public void setAlignment(int alignment)

Parameters

alignment

The alignment mode to use for positoining the text on the label.

Description

This method sets the alignment mode to use for positioning the text on the label. If an invalid value is passed as an alignment mode, then an IllegalArgumentException is thrown.

Imports

import java.awt.Label;

Returns

None.

See Also

The getAlignment method of the IllegalArgumentException class

Example

In the following example this method is used to set the alignment mode of a label.

import java.awt.*;

public class LabelTest extends Frame

public static void main(String args[])

setText(String)

ClassName

Label

Purpose

To change the text string displayed on the label.

Syntax

public void setText(String label)

Parameters

label

The text for the label.

Description

This method sets the text string displayed on the label.

Imports

import java.awt.Label;

Returns

None.

See Also

The getText method

Example

This method is used in the following sample code.

import java.awt.*;

public class LabelTest extends Frame

public static void main(String args[])

Panel

Purpose

A class that implements a generic container in which other components can be laid out.

Syntax

public class Panel extends Container

Description

Panels are commonly used as windows in which to arrange other components (such as Buttons, Labels, etc.). The FlowLayout layout manager is the default layout manager used for all Panels. Panels do not have a title bar and, unlike Frame windows, they cannot be used as top-level windows. The methods of the Container and Component classes can be invoked on Panels. Refer to the examples in Chapter 2 and Chapter 3 for more information. Figure 4-9 shows the inheritance hierarchy for the Panel class.

PackageName

java.awt

Imports

import java.awt.Panel;

Constructors

public Panel()

Parameters

None.

Example

In this example, buttons are added to a Panel window within a Frame window.

import java.awt.*;

public class PanelTest


Figure 4-9  Inheritance hierarchy for the Panel class

addNotify()

ClassName

Panel

Purpose

To create a peer for this Panel object.

Syntax

public synchronized void addNotify()

Parameters

None.

Description

This method creates a peer for this Panel object that you can use to change the appearance of the panel window without changing its functionality. The addNotify method is the earliest stage in the creation of a component at which platform specific resources (such as color, fonts, and fontmetrics) may be determined. Classes that override this method must first call super.addNotify() before doing any other processing in this method.

Imports

import java.awt.Panel;

Returns

None.

See Also

The PanelPeer interface

Example

Refer to the example listed in the addNotify method of the Canvas class in this chapter and also to the section on PanelPeer interfaces in Chapter 9.

Scrollbar

Purpose

A class that represents a scrollbar.

Syntax

public class Scrollbar extends Component

Description

This class implements a scrollbar object. Applications use scrollbars to scroll the data or image displayed on the screen. The scrollbar thumb position indicates the position of the visible portion of the image or data within a larger image or data buffer. Scrollbars are associated with a viewing area, and by dragging the thumb of the scrollbar, a user can change the image or data displayed in the viewing area. Figure 4-10 shows the inheritance hierarchy for the Scrollbar class.

PackageName

java.awt

Imports

import java.awt.Scrollbar;

Constructors

public Scrollbar()
public Scrollbar(int orientation)
public Scrollbar(int orientation, int value, int visible, int minimum, int maximum)

Parameters

orientation

The orientation of the scrollbar.

value

The current value of the scrollbarís thumb position.

visible

The size of the visible region of the area that is being scrolled using the scrollbar.

minimum

The minimum value of the scrollbar.

maximum

The maximum value of the scrollbar.

Example

This sample code shows how to construct Scrollbar objects.

import java.awt.*;

public class TestScroll extends Frame
public static void main(String args[])


Figure 4-10  Inheritance hierarchy for the Scrollbar class

addNotify()

ClassName

ScrollBar

Purpose

Creates a peer object for this Scrollbar object.

Syntax

public synchronized void addNotify()

Parameters

None.

Description

Using this method one can change the appearance of the scrollbar without changing its functionality. The addNotify method is the earliest stage in the creation of a component at which platform specific resources such as color, fonts and fontmetrics may be determined. Classes that override this method must first call super.addNotify() before doing any other processing in this method.

Imports

import java.awt.Scrollbar;

Returns

None.

See Also

The ScrollbarPeer class

Example

Refer to the example listed in the addNotify method of the Canvas class in this chapter and also to the section on ScrollbarPeer interfaces in Chapter 9.

getLineIncrement()

ClassName

Scrollbar

Purpose

To get the step size, set for decrements/increments when the line up/down arrow buttons of the scrollbar are invoked.

Syntax

public int getLineIncrement()

Parameters

None.

Description

This method returns an integer that represents the step size that will increment line.

Imports

import java.awt.Scrollbar;

Returns

This method returns an integer that represents the line increment step size.

Example

The following example demonstrates the use of this method in an application.

import java.awt.*;

public class TestScroll extends Frame
public static void main(String args[])

getMaximum()

ClassName

Scrollbar

Purpose

To determine the value of the maximum position of the scrollbar thumb

Syntax

public int getMaximum()

Parameters

None.

Description

This method gets the value for the maximum position of the thumb for this Scrollbar object.

Imports

import java.awt.Scrollbar;

Returns

This method returns an integer value that represents the maximum position of the Scrollbar object.

Example

The following example demonstrates the use of this method in an application.

import java.awt.*;

public class TestScroll extends Frame
public static void main(String args[])

getMinimum()

ClassName

Scrollbar

Purpose

To determine the minimum position of the scrollbar thumb.

Syntax

public int getMinimum()

Parameters

None.

Description

This method gets the value for the minimum position of the thumb for this Scrollbar object.

Imports

import java.awt.Scrollbar;

Returns

This method returns an integer that represents the minimum position of the Scrollbar object.

Example

The following example demonstrates the use of this method in an application.

import java.awt.*;

public class TestScroll extends Frame
public static void main(String args[])

getPageIncrement()

ClassName

Scrollbar

Purpose

Gets the step size, set for decrements/increments when the page up/down actions of the scrollbar are invoked.

Syntax

public int getPageIncrement()

Parameters

None.

Description

This method returns an integer that represents the page increment step size.

Imports

import java.awt.Scrollbar;

Returns

This method returns an integer that represents the page increment step size.

Example

The following example demonstrates the use of this method in an application.

import java.awt.*;

public class TestScroll extends Frame
public static void main(String args[])

getOrientation()

ClassName

Scrollbar

Purpose

To determine the orientation of the scrollbar.

Syntax

public int getOrientation()

Parameters

None.

Description

This method gets the value for the orientation of this Scrollbar object.

Imports

import java.awt.Scrollbar;

Returns

This method returns an integer that represents the orientation of this ScrollBar object. The value returned is either Scrollbar.HORIZONTAL or Scrollbar.VERTICAL.

Example

The following example demonstrates the use of this method in an application.

import java.awt.*;

public class TestScroll extends Frame
public static void main(String args[])

getValue()

ClassName

Scrollbar

Purpose

Determines the value of the current position of the scrollbar thumb

Syntax

public int getValue()

Parameters

None.

Description

This method gets the value for the current position of the thumb for this Scrollbar object.

Imports

import java.awt.Scrollbar;

Returns

This method returns an integer that represents the current position of the Scrollbar object.

Example

The following example demonstrates the use of this method in an application.

import java.awt.*;

public class TestScroll extends Frame
public static void main(String args[])

getVisible()

ClassName

Scrollbar

Purpose

To determine the size of the visible portion of the scrollbar.

Syntax

public int getVisible()

Parameters

None.

Description

This method gets the value for the visible portion of this Scrollbar object.

Imports

import java.awt.Scrollbar;

Returns

This method returns an integer that represents the visible portion of this Scrollbar object.

Example

The following example demonstrates the use of this method in an application.

import java.awt.*;

public class TestScroll extends Frame
public static void main(String args[])

paramString()

ClassName

Scrollbar

Purpose

To return the parameter string associated with this Scrollbar object

Syntax

protected String paramString()

Parameters

None.

Description

This method returns the parameter values associated with a Scrollbar object. The values are prefixed by short descriptive tags. This protected method cannot be invoked from an application, but is invoked by the toString method of the Component class.

Imports

import java.awt.Scrollbar;

Returns

The return value is a String that contains the values of the parameters for the Scrollbar object. The values are prefixed by a short textual description of the property they denote.

See Also

The toString and paramString methods of the Component class

Example

The following example demonstrates the use of this method in an application.

import java.awt.*;

public class TestScroll extends Frame
public static void main(String args[])

setLineIncrement(int)

ClassName

Scrollbar

Purpose

Sets the step size for decrements/increments when the line up/down arrow buttons of the scrollbar are invoked.

Syntax

public void setLineIncrement(int l)

Parameters

l

The line increment size.

Description

This method specifies the amount that the area is to be scrolled when the user invokes the line up/down arrow buttons of the scrollbar. The position of the scrollbar thumb within the scrollbar is also updated proportional to the value specified in this method.

Imports

import java.awt.Scrollbar;

Returns

None.

Example

The following example demonstrates the use of this method in an application.

import java.awt.*;

public class TestScroll extends Frame
public static void main(String args[])

setPageIncrement(int)

ClassName

Scrollbar

Purpose

Sets the step size for decrements/increments when the page up/down actions of the scrollbar are invoked.

Syntax

public void setPageIncrement(int l)

Parameters

l

The page increment size.

Description

This method specifies the amount that the area is to be scrolled when the user invokes the page up/down actions. The position of the scrollbar thumb within the scrollbar is also updated proportional to the value specified in this method

Imports

import java.awt.Scrollbar;

Returns

None.

Example

The following example demonstrates the use of this method in an application.

import java.awt.*;

public class TestScroll extends Frame
public static void main(String args[])

setValue(int)

ClassName

Scrollbar

Purpose

Sets the value of the current position of this Scrollbar to the specified value.

Syntax

public void setValue(int value)

Parameters

value

The new value for the current position of the Scrollbar. If this value is less than the minimum value of the scrollbar, then it becomes the new minimum value of the scrollbar. Similarly, if this value is more than the maximum value of the scrollbar, then it becomes the new maximum value of the scrollbar.

Description

This method sets the value for the current position of the thumb for this Scrollbar object.

Imports

import java.awt.Scrollbar;

Returns

None.

Example

The following example demonstrates the use of this method in an application.

public class TestScroll extends Frame
public static void main(String args[])

setValues(int, int, int, int)

ClassName

Scrollbar

Purpose

Sets various parameters associated with this ScrollBar object.

Syntax

public void setValues(int value, int visible, int minimum, int maximum)

Parameters

value

The position of the scrollbar thumb in the current window.

visible

The size of the visible region of the area being scrolled using the scrollbar.

minimum

The minimum value of the scrollbar.

maximum

The maximum value of the scrollbar.

Description

This method provides a convenient way to set the various parameters of this Scrollbar object.

Imports

import java.awt.Scrollbar;

Returns

None.

Example

The following example demonstrates the use of this method in an application.

public class TestScroll extends Frame
public static void main(String args[])

LayoutManager

Purpose

An interface for classes that need to lay out Components in Containers.

Syntax

public interface LayoutManager extends Object

Description

This interface is used to implement the mechanisms required of classes that know how to lay out Containers. All the layout managers supplied with the Java AWT implement this interface.

PackageName

java.awt

Imports

import java.awt.LayoutManager;

Constructors

None.

Parameters

None.

Example

See the examples for FlowLayout and GridLayout.

addLayoutComponent(String, Component)

Interface

LayoutManager

Purpose

To add the specified component to the layout, associating the component with the specified name.

Syntax

public abstract void addLayoutComponent(String name, Component comp)

Parameters

name

Name of the area where the component should be added.

comp

Component object to be added.

Description

This method should be defined in any class that implements the LayoutManager interface.

Imports

import java.awt.LayoutManager;

Returns

None.

See Also

The Container class

Example

The following example demonstrates the implementation of this method.

import java.awt.*

public class MyLayout implements LayoutManager

/* Implement all the other methods of the LayoutManager
interface */

layoutContainer(Container)

Interface

LayoutManager

Purpose

To lay out the specified container.

Syntax

public abstract void layoutContainer(Container parent)

Parameters

parent

The Container object to be laid out.

Description

This method causes the specified container to be laid out. It should be defined in any class that implements the LayoutManager interface.

Imports

import java.awt.LayoutManager;

Returns

None.

See Also

The Container class

Example

The following sample code for a custom layout manager shows the implementation of this function.

import java.awt.*

public class MyLayout implements LayoutManager

/* Implement all the other methods of the LayoutManager
interface */

minimumLayoutSize(Container)

Interface

LayoutManager

Purpose

To calculate the minimum size required to lay out the container, taking into account the components in the specified container.

Syntax

public abstract Dimension minimumLayoutSize(Container parent)

Parameters

parent

The Container that holds the components that need to be laid out.

Description

This method should be defined in any class that implements the LayoutManager interface.

Imports

import java.awt.LayoutManager;

Returns

The return type of this method is Dimension. This return value contains the minimum height and width required to layout the container in the specified panel.

See Also

The Container class

Example

Here is an extract from a class that implements the LayoutManager interface.

import java.awt.*

public class MyLayout implements LayoutManager
/* Implement all the other methods of the LayoutManager
interface */

preferredLayoutSize(Container)

Interface

LayoutManager

Purpose

To calculate the preferred dimensions required to lay out the container, taking into account the components in the specified container.

Syntax

public abstract Dimension preferredLayoutSize(Container parent)

Parameters

parent

The Container that holds the components that need to be laid out.

Description

This method should be defined in any class that implements the LayoutManager interface.

Imports

import java.awt.LayoutManager;



Returns

The return type of this method is Dimension. This return value contains the preferred height and width required to lay out the container in the specified panel.

See Also

The Container Class

Example

The following example demonstrates the implementation of this method.

import java.awt.*

public class MyLayout implements LayoutManager
/* Implement all the other methods of the LayoutManager
interface */

removeLayoutComponent(Component)

Interface

LayoutManager

Purpose

To remove the specified component from the layout.

Syntax

public abstract void removeLayoutComponent(Component comp)

Parameters

comp

The Component to be removed from the layout.

Description

This method should be defined in any class that implements the LayoutManager interface.

Imports

import java.awt.LayoutManager;

Returns

None.

See Also

The Container class

Example

The following sample code demonstrates the implementation of this method in a class that implements a custom layout manager.

import java.awt.*

public class MyLayout implements LayoutManager

/* Implement all the other methods of the LayoutManager
interface */

FlowLayout

Purpose

A simple layout manager that lays out components in rows (from left to right).

Syntax

public class FlowLayout extends Object implements LayoutManager

Description

This class implements the LayoutManager interface and is used to lay out components in rows. The components are laid out from left to right and centered within their row. This is the default layout manager for all Panels. Figure 4-11 shows the inheritance hierarchy for the FlowLayout class.

PackageName

java.awt

Imports

import java.awt.flowlayout;

Constructorts

public FlowLayout()
public FlowLayout(int align)
public FlowLayout(int align, int hgap, int vgap)

Parameters

align

The alignment to use for laying out components (can be LEFT,CENTER, or RIGHT).

hgap

The horizontal gap to leave between components.

vgap

The vertical gap to leave between components.

Example

This sample code shows how to construct FlowLayout objects using the different FlowLayout constructors.

/* Default FlowLayout constructor */
FlowLayout f1 = new FlowLayout();

/* FlowLayout object that aligns components to the left */
FlowLayout f2 = new FlowLayout(FlowLayout.LEFT);

/* FlowLayout object that aligns components to the left, with a
horizontal gap of 30 units between components and a vertical gap
of 0 units */
FlowLayout f3 = new FlowLayout(FlowLayout.LEFT, 30, 0);


Figure 4-11  Inheritance hierarchy for the FlowLayout class

addLayoutComponent(String, Component)

ClassName

FlowLayout

Purpose

To add the specified component to the area in the layout associated with the specified name.

Syntax

public void addLayoutComponent(String name, Component comp)

Parameters

name

Name of the component to be added.

comp

Component object to be added.

Description

The FlowLayout class does not divide the layout area into subareas, and hence does not need to implement any functionality for this method. In order to conform to the LayoutManager interface, this method is an empty stub in the FlowLayout implementation.

Imports

import java.awt.FlowLayout;

Returns

None.

See Also

The Container class; the LayoutManager interface

Example

This code invokes the Containerís add method, which in turn invokes this method.

/* Create a Container for the components */
Panel p = new Panel();
/* set the layout manager for this panel */
p.setLayout(new FlowLayout());

/* add the components to be laid out */
/* This results in the component being added to the layout manager */
p.add('North', new Button('This')); // the named areas carry
significance only for the
p.add('West', new Button('demonstration')); // BorderLayout layout
manager, other layout
p.add('Center', new Button('is')); // managers ignore
this parameter
p.add('East', new Button('really'));
p.add('South', new Button('cool !'));

layoutContainer(Container)

ClassName

FlowLayout

Purpose

To lay out the specified container in rows, aligning the components within each row.

Syntax

public void layoutContainer(Container parent)

Parameters

parent

Container object to be laid out.

Description

The components are laid out from left to right and aligned within a row. The default alignment is CENTER, but a different alignment (either LEFT or RIGHT) can be specified while constructing the FlowLayout object. The horizontal gap between components in a row and the vertical gap between rows can also be specified in the FlowLayout constructor. Applications do not directly invoke this method. The layout method of the Container class results in a call to this method. The layout method of the Container class is invoked when the Container needs to be displayed on the screen.

Imports

import java.awt.FlowLayout;

Returns

None.

See Also

The LayoutManager interface; the Container class

Example

In the following example, a Frame window is created and displayed.

import java.awt.*;
import java.applet.Applet;

public class LayoutDemo extends Applet

minimumLayoutSize(Container)

ClassName

FlowLayout

Purpose

To calculate the minimum size required to lay out the container, taking into account the components in the specified container.

Syntax

public Dimension minimumLayoutSize(Container parent)

Parameters

parent

Container containing components that need to be laid out.

Description

This method calculates and returns the minimum dimensions required by the FlowLayout manager to lay out the components.

Imports

import java.awt.FlowLayout;

Returns

The return type of this method is Dimension. This return value contains the minimum height and width required to lay out the container in the specified panel.

See Also

The Container class; the LayoutManager interface

Example

The following sample code is an example of this method in an application.

/* Create a Container for the components */
Panel p = new Panel();
/* set the layout manager for this panel */
p.setLayout(new FlowLayout());

/* add the components to the Container */
/* This results in the component being added to the layout manager */
p.add('North', new Button('This'));
p.add('Center', new Button('is'));
p.add('South', new Button('cool !'));

/* Get the minimum dimensions of the Container */
/* This results in a call to the minimumLayoutSize() method of the
layout manager */
Dimension d = p.minimumSize();

preferredLayoutSize(Container)

ClassName

FlowLayout

Purpose

To calculate the preferred dimensions for this layout, taking into account the components in the specified container.

Syntax

public Dimension preferredLayoutSize(Container target)

Parameters

target

Container that needs to be laid out.

Description

This method computes the ideal width and height required by this layout. The values returned have no effect unless the program specifically enforces these dimensions.

Imports

import java.awt.FlowLayout;

Returns

The return type of this method is Dimension. This return value contains the ideal height and width required to lay out the container in the specified panel.

See Also

The Container class; the LayoutManager interface

Example

The following sample code demonstrates the use of this method.

/* Create a Container for the components */
Panel p = new Panel();
/* set the layout manager for this panel */
p.setLayout(new FlowLayout());

/* add the components to the Container */
p.add('North', new Button('This'));
p.add('Center', new Button('is'));
p.add('South', new Button('cool !'));

/* Get the ideal dimensions of the Container */
/* This results in a call to the preferredLayoutSize()
method of the layout manager */
Dimension d = p.preferredSize();

removeLayoutComponent(Component)

ClassName

FlowLayout

Purpose

To remove the specified component from the layout.

Syntax

public void removeLayoutComponent(Component comp)

Parameters

comp

Component to be removed from the layout.

Description

This method is a dummy stub in the FlowLayout class, as this layout manager doesnít need to maintain associations between components and areas on the display. Applications do not directly invoke this method. The remove method of the Container class results in a call to this method.

Imports

import java.awt.FlowLayout;

Returns

None.

See Also

The Container class; the LayoutManager interface

Example

The sample code adds buttons to a Panel and then removes one of the buttons.

/* Create a Container for the components */
Panel p = new Panel();
/* set the layout manager for this panel */
p.setLayout(new FlowLayout());

/* add the components to be laid out */
/* This results in the component being added to the layout manager */
Button b1 = new Button('Good');
Button b2 = new Button('Bad');
Button b3 = new Button('Day');
/* add the buttons to the container */
p.add(b1);
p.add(b2);
p.add(b3);
/* remove a specific button from the container */
/* The Containerís remove() method invokes the layout
managerís removeComponent() method */
p.remove(b2);

toString()

ClassName

FlowLayout

Purpose

To represent the FlowLayout objectís values as a String.

Syntax

public String toString()

Parameters

None.

Description

The values of the horizontal gap variable, the vertical gap variable, and the alignment mode variable for this layout are returned as a String object.

Imports

import java.awt.FlowLayout;

Returns

The return value is a String that contains the values of the properties for the FlowLayout object. The values are prefixed by a short textual description of the property they denote.

See Also

The toString method of the Object class

Example

This method is implemented in the following function.

void printLayoutInfo(LayoutManager layout)

GridLayout

Purpose

A layout manager that creates a grid with the specified number of rows and columns and lays out components on the grid.

Syntax

public class GridLayout extends Object implements LayoutManager

Description

This class implements the LayoutManager interface and is used to lay out components in grids. It makes all the components of equal size and lays them out on the grid. Figure 4-12 shows the inheritance hierarchy for the GridLayout class.

PackageName

java.awt

Imports

import java.awt.GridLayout;

Constructors

public GridLayout(int rows, int cols)
public GridLayout(int rows, int cols, int hgap, int vgap)

Parameters

rows

The number of rows in the grid.

cols

The number of columns in the grid.

hgap

The horizontal gap to leave between components.

vgap

The vertical gap to leave between components.

Example

Here is sample source code that illustrates GridLayout construction.

/* GridLayout constructor to lay out components in a single row
with any number of columns */
GridLayout g1 = new GridLayout(1, 0);

/* GridLayout constructor specifying a grid of 3 rows and 2 columns */
GridLayout g2 = new GridLayout(3, 2);

/* GridLayout object that lays out components in a grid consisting
of 3 rows and 2 columns. The horizontal gap between columns is
20 units and the vertical gap between rows is 10 units */
GridLayout g3 = new GridLayout(3, 2, 20, 10);


Figure 4-12  Inheritance hierarchy for the GridLayout class

addLayoutComponent(String, Component)

ClassName

GridLayout

Purpose

To add the specified component to the layout, associating the component with the specified name.

Syntax

public void addLayoutComponent(String name, Component comp)

Parameters

name

Name of the component to be added.

comp

Component object to be added.

Description

The GridLayout class does not divide the layout area into subareas, and hence does not need to implement any functionality for this method. In order to conform to the LayoutManager interface, this method is an empty stub in the GridLayout implementation.

Imports

import java.awt.GridLayout;

Returns

None.

See Also

The Container class; the LayoutManager interface

Example

Refer to the example given under the corresponding function in the FlowLayout class.

layoutContainer(Container)

ClassName

GridLayout

Purpose

To lay out the specified container in rows, aligning the components within each row.

Syntax

public void layoutContainer(Container parent)

Parameters

parent

Container object to be laid out.

Description

This method lays out the components in the container, in a grid. Applications do not directly invoke this method. The layout method of the Container class results in a call to this method.

Imports

import java.awt.GridLayout;

Returns

None.

See Also

The LayoutManager interface; the Container class

Example

Refer to the example given under the corresponding function in the FlowLayout class.

minimumLayoutSize(Container)

ClassName

GridLayout

Purpose

To calculate the minimum size required to lay out the container, taking into account the components in the specified container.

Syntax

public Dimension minimumLayoutSize(Container parent)

Parameters

parent

Container that needs to be laid out.

Description

This method calculates and returns the minimum dimensions required by the GridLayout manager to lay out the components contained within the specified container. The minimum dimensions are calculated according to the following formulae:
Minimum width = (Left + Right insets of parent) + (number of columns * width of widest component in parent) + ((number of columns -1)*inter-column gap)
Minimum height = (Top + Bottom insets of parent) + (number of rows * height of tallest component in parent) + ((number of rows -1)*inter-row gap)

Imports

import java.awt.GridLayout;

Returns

The return type of this method is Dimension. This return value contains the minimum height and width required to lay out the container in the specified panel.

See Also

The Container class; the LayoutManager interface

Example

Refer to the example given under the corresponding function in the FlowLayout class.

preferredLayoutSize(Container)

ClassName

GridLayout

Purpose

To calculate the preferred dimensions for this layout, taking into account the components in the specified container.

Syntax

public Dimension preferredLayoutSize(Container target)

Parameters

target

Container that needs to be laid out.

Description

This method computes the ideal width and height required by this layout. The values returned have no effect unless the program specifically enforces these dimensions.

Imports

import java.awt.GridLayout;

Returns

This method returns a Dimension object. This return value contains the ideal height and width required to lay out the container in the specified panel.

See Also

The container class; the LayoutManager interface

Example

Refer to the example given under the corresponding function in the FlowLayout class.

removeLayoutComponent(Component)

ClassName

GridLayout

Purpose

To remove the specified component from the layout.

Syntax

public void removeLayoutComponent(Component comp)

Parameters

comp

Component to be removed from the layout.

Description

This method is a dummy stub in the GridLayout class, as this layout manager doesnít need to maintain associations between components and areas on the display.

Imports

import java.awt.GridLayout;

Returns

None.

See Also

The Container class; the LayoutManager interface

Example

Refer to the example given under the corresponding function in the FlowLayout class.

toString()

ClassName

GridLayout

Purpose

To represent the values of the GridLayout object as a String.

Syntax

public String toString()

Parameters

None.

Description

This method returns a String representation of this objectís values, namely, the horizontal gap, the vertical gap, the number of rows, and the number of columns. Each value is prefixed with a short descriptive tag.

Imports

import java.awt.GridLayout;

Returns

This method returns a String containing the values of the GridLayout object, with each value prefixed by a descriptive tag.

See Also

The toString method of the Object class

Example

Refer to the example given under the corresponding function in the FlowLayout class.

BorderLayout

Purpose

A layout manager that divides a rectangular area into five named areas and lays out components in each of these named areas.

Syntax

public class BorderLayout extends Object implements LayoutManager

Description

This layout manager divides the area of the Container into five named areas: North, South, East, West, and Center. A container that uses this layout manager must add a component to a named area. The preferred dimensions of the components, added to the North, South, East, and West areas, are honored and the component added to the Center area occupies all the remaining space. This is the default layout manager for all Window objects (such as Frame windows and Dialog windows). Figure 4-13 shows the inheritance hierarchy for the BorderLayout class.

PackageName

java.awt

Imports

import java.awt.BorderLayout;

Constructors

public BorderLayout()
public BorderLayout(int hgap, int

Parameters

hgap

The horizontal gap to leave between the named areas.

vgap

The vertical gap to leave between the named areas.

Example

Here is sample source code that illustrates BorderLayout construction.

/* default BorderLayout constructor */
BorderLayout b1 = new BorderLayout();

// horizontal gap between named areas is 20 units and the vertical
gap is 10 units */
BorderLayout b2 = new BorderLayout(20, 10);


Figure 4-13  Inheritance hierarchy for the BorderLayout class

addLayoutComponent(String, Component)

ClassName

BorderLayout

Purpose

To add the component to the named area of the container.

Syntax

public void addLayoutComponent(String name, Component comp)

Parameters

name

Name of the area within the container to add the component to.

comp

Component object to be added.

Description

The BorderLayout layout manager divides the Container into five areas and hence, the parameter name can be one of North, South, East, West, or Center. The specified component is associated with the area and is added to that portion of the Container.

Imports

import java.awt.BorderLayout;

Returns

None.

See Also

The Container class; the LayoutManager interface

Example

Refer to the example given under the corresponding function in the FlowLayout class.

layoutContainer(Container)

ClassName

BorderLayout

Purpose

To lay out the specified container by laying out the components in the areas where they have been added.

Syntax

public void layoutContainer(Container parent)

Parameters

parent

Container object to be laid out.

Description

This method lays out the components in the container, in the named areas where they were added. Applications do not directly invoke this method. The layout method of the Container class results in a call to this method.

Imports

import java.awt.BorderLayout;

Returns

None.

See Also

The LayoutManager interface; the class Container

Example

Refer to the example given under the corresponding function in the FlowLayout class.

minimumLayoutSize(Container)

ClassName

BorderLayout

Purpose

To calculate the minimum size required to lay out the container, taking into account the components in the specified container.

Syntax

public Dimension minimumLayoutSize(Container parent)

Parameters

parent

Container that needs to be laid out.

Description

This method calculates and returns the minimum dimensions required by the BorderLayout manager to lay out the components contained within the specified container.

Imports

import java.awt.BorderLayout;

Returns

This method returns a Dimension object. This return value contains the minimum height and width required to lay out the container in the specified panel.

See Also

The Container class; the LayoutManager interface

Example

Refer to the example given under the corresponding function in the FlowLayout class.

preferredLayoutSize(Container)

ClassName

BorderLayout

Purpose

To calculate the preferred dimensions for this layout, taking into account the components in the specified container.

Syntax

public Dimension preferredLayoutSize(Container target)

Parameters

target

The Container that needs to be laid out.

Description

This method computes the ideal width and height required by this layout. The values returned have no effect unless the program specifically enforces these dimensions.

Imports

import java.awt.BorderLayout;

Returns

This method reutrns a Dimension object. This return value contains the ideal height and width required to lay out the container in the specified panel.

See Also

The Container class; the LayoutManager interface

Example

Refer to the example given under the corresponding function in the FlowLayout class.

removeLayoutComponent(Component)

ClassName

BorderLayout

Purpose

To remove the specified component from the layout.

Syntax

public void removeLayoutComponent(Component comp)

Parameters

comp

Component to be removed from the layout.

Description

This method disassociates the component being removed from the named area to which it was added.

Imports

import java.awt.BorderLayout;

Returns

None.

See Also

The Container class; the LayoutManager interface

Example

Refer to the example given under the corresponding function in the FlowLayout class.

toString()

ClassName

BorderLayout

Purpose

To represent the values of the BorderLayout object as a String.

Syntax

public String toString()

Parameters

None.

Description

This method returns a String representation of this BorderLayout objectís values, namely the horizontal gap and the vertical gap between the named areas, that the BorderLayout organizes its components in. Each value is prefixed with a short descriptive tag.

Imports

import java.awt.BorderLayout;

Returns

This method returns a String containing the values of the BorderLayout object, each value prefixed by a descriptive tag.

See Also

The toString method of the Object class

Example

Refer to the example given under the corresponding function in the FlowLayout class.

CardLayout

Purpose

A powerful layout manager that a container can use to lay out its components as a stack of cards, only one card being visible at any point of time.

Syntax

public class CardLayout extends Object implements LayoutManager

Description

This layout manager allows the Container to use the same real estate on the screen to present different views of different components. These views are arranged in a fashion similar to that of a deck of cards and the individual views can be flipped back and forth on the view stack. Figure 4-14 shows the inheritance hierarchy for the CardLayout class.

PackageName

java.awt

Imports

import java.awt.CardLayout;

Constructors

public CardLayout()
public CardLayout(int hgap, int vgap)

Parameters

hgap

The horizontal gap to leave between components on each card.

vgap

The vertical gap to leave between components on each card.

Example

Here is sample source code that illustrates CardLayout construction. The chapter project demonstrates the use of this layout manager in a more complete manner.

CardLayout c1 = new CardLayout(); // default constructor

// horizontal gap between named areas is 20 units and the vertical
gap is 10 units */
CardLayout b2 = new CardLayout(20, 10);


Figure 4-14  Inheritance hierarchy for the CardLayout class

addLayoutComponent(String, Component)

ClassName

CardLayout

Purpose

To add the specified component to the layout, associating the component with the specified name.

Syntax

public void addLayoutComponent(String name, Component comp)

Parameters

name

Name of the component to be added.

comp

Component object to be added.

Description

The CardLayout class maintains the stack of cards to display. This stack is updated as components are added to the card stack. The parameter name can be any user-specified string. This parameter name is used by the show method to bring the named card into view.

Imports

import java.awt.CardLayout;

Returns

None.

See Also

The Container class; the LayoutManager interface; the show method of the CardLayout class

Example

The chapter project uses a CardLayout to display different views. Refer to it for more details.

first(Container)

ClassName

CardLayout

Purpose

To make the first card in the card stack visible.

Syntax

public void first(Container parent)

Parameters

parent

The parent Container object that this CardLayout object is the layout manager for.

Description

The first card in the card stack is brought into view and all the Components on this card are displayed.

Imports

import java.awt.CardLayout;

Returns

None.

Example

This method is used in the project at the end of this chapter.

last(Container)

ClassName

CardLayout

Purpose

To make the last card in the card stack visible.

Syntax

public void last(Container parent)

Parameters

parent

The parent Container object that this CardLayout object is the layout manager for.

Description

The card at the bottom of the card stack is brought into view.

Imports

import java.awt.CardLayout;

Returns

None.

Example

The project at the end of this chapter uses this method.

layoutContainer(Container)

ClassName

CardLayout

Purpose

To lay out the specified container in rows, aligning the components within each row.

Syntax

public void layoutContainer(Container parent)

Parameters

parent

Container object to be laid out.

Description

This method lays out the components in the container, in the named areas where they were added. Applications do not directly invoke this method. The layout method of the Container class results in a call to this method.

Imports

import java.awt.CardLayout;

Returns

None.

See Also

The LayoutManager interface; the Container class

Example

Refer to the example given under the corresponding function in the FlowLayout class and to the chapter project.

minimumLayoutSize(Container)

ClassName

CardLayout

Purpose

To calculate the minimum size required to lay out the container, taking into account the components in the specified container.

Syntax

public Dimension minimumLayoutSize(Container parent)

Parameters

parent

Container that needs to be laid out;

Description

This method calculates and returns the minimum dimensions required by the CardLayout manager to lay out the components contained within the specified container.

Imports

import java.awt.CardLayout;

Returns

The return type of this method is Dimension. This return value contains the minimum height and width required to lay out the container in the specified panel.

See Also

The Container class; the LayoutManager interface

Example

Refer to the example given under the corresponding function in the FlowLayout class and to the chapter project.

next(Container)

ClassName

CardLayout

Purpose

To make the next card in the card stack visible. If the current card is the bottom-most card in the stack then the first card is made visible.



Syntax

public void next(Container parent)

Parameters

parent

The parent Container object that this CardLayout object is the lay out manager for.

Description

The card currently in view is hidden and the card just below it is displayed.

Imports

import java.awt.CardLayout;

Returns

None.

Example

The project at the end of this chapter uses this method.

preferredLayoutSize(Container)

ClassName

CardLayout

Purpose

To calculate the preferred dimensions for this layout, taking into account the components in the specified container.

Syntax

public Dimension preferredLayoutSize(Container target)

Parameters

target

Container that needs to be laid out.

Description

This method computes the ideal width and height required by this layout. The values returned have no effect unless the program specifically enforces these dimensions.

Imports

import java.awt.CardLayout;

Returns

The return type of this method is Dimension. This return value contains the ideal height and width required to lay out the container in the specified panel.

See Also

The Container class; the LayoutManager interface

Example

Refer to the example given under the corresponding function in the FlowLayout class.

previous(Container)

ClassName

CardLayout

Purpose

To make the previous card in the card stack visible. The previous card to the top-most card in the stack is deemed to be the card at the bottom of the stack.

Syntax

public void previous(Container parent)

Parameters

parent

The parent Container object that this CardLayout object is the layout manager for

Description

The card currently in view is hidden and the card just above it is displayed.

Imports

import java.awt.CardLayout;

Returns

None.

Example

The project at the end of this chapter uses this method.

removeLayoutComponent(Component)

ClassName

CardLayout

Purpose

To remove the specified component from the layout.

Syntax

public void removeLayoutComponent(Component comp)

Parameters

comp

Component to be removed from the layout.

Description

This method disassociates the component being removed from the named area to which it was added.

Imports

import java.awt.CardLayout;

Returns

None.

See Also

The Container class; the LayoutManager interface

Example

Refer to the example given under the corresponding function in the FlowLayout class.

show(Container, String)

ClassName

CardLayout

Purpose

To make the specified card visible.

Syntax

public void show(Container parent, String name)

Parameters

parent

The parent Container object that this CardLayout object is the layout manager for.

name

Name of the card in the stack.

Description

The name parameter is specified when adding cards to the stack. This name is used to bring the specified card into view.

Imports

import java.awt.CardLayout;

Returns

None.

Example

The project at the end of this chapter uses this method.

toString()

ClassName

CardLayout

Purpose

To represent the parameter values of the CardLayout object as a String.

Syntax

public String toString()

Parameters

None.

Description

This method returns a String representation of this CardLayout objectís values, namely, the horizontal and vertical gap to leave between components. Each value is prefixed with a short descriptive tag.

Imports

import java.awt.CardLayout;

Returns

This method returns a String containing the values of the CardLayout object, each value prefixed by a descriptive tag.

See Also

The toString method of the Object class

Example

Refer to the example given under the corresponding function in the FlowLayout class and to the chapter project.

GridBagLayout

Purpose

A very sophisticated layout manager that can lay out individual components using different constraints, in a manner such that components can be of different sizes and can be aligned vertically and horizontally.

Syntax

public class GridBagLayout extends Object implements LayoutManager

Description

This is the most powerful of all the layout managers that the Abstract Windowing Toolkit provides. Consequently, it is also the most complex layout manager. This layout manager can lay out components on a grid of cells, with each component occupying one or more cells in the grid. The group of cells occupied by a component is known as its display area. A GridBagConstraints object is associated with each component and these constraints instruct the layout manager to lay out the component in a particular manner. Refer to the GridBagConstraints class in this chapter for more information on customizing the appearance of a Container using a GridBagLayout layout manager. Figure 4-15 shows the inheritance hierarchy for the GridBagLayout class.

PackageName

java.awt

Imports

import java.awt.GridBagLayout;

Constructors

public GridBagLayout()

Parameters

None.

Example

Refer to the chapter project for a detailed example of a GridBagLayout layout manager


Figure 4-15  Inheritance hierarchy for the GridBagLayout class

addLayoutComponent(String, Component)

ClassName

GridBagLayout

Purpose

To add the specified component to the layout.

Syntax

public void addLayoutComponent(String name, Component comp)

Parameters

name

Name of the component to be added.

comp

Component object to be added.

Description

The GridBagLayout uses a GridBagConstraints object to lay out a component and does not associate a name with a component. In order to conform to the LayoutManager interface, this method exists but is an empty stub.

Imports

import java.awt.GridBagLayout;

Returns

None.

See Also

The Container class; the LayoutManager interface

Example

Refer to the chapter project to see how components are added to a GridBagLayout and how a GridBagConstraints object instructs this layout manager how to lay out the particular component.

AdjustForGravity(GridBagConstraints, Rectangle)

ClassName

GridBagLayout

Purpose

To modify the position and dimensions of the component depending on the specified constraints.

Syntax

protected void AdjustForGravity(GridBagConstraints c, Rectangle r)

Parameters

c

GridBagConstraints object specifying the constraints.

r

Rectangle specifying the coordinates and dimensions of a component.

Description

The coordinates of the rectangle r and the height and width dimensions are set according to the constraints, specified in the GridBagConstraints object c. The GridBagConstraints object specifies the geometry constraint, as well as any padding that is to be added to the size of the component.

Imports

import java.awt.GridBagLayout;

Returns

None.

Example

This method is a protected method in the GridBagLayout class and is used internally by the GridBagLayout implementation.

ArrangeGrid(Container)

ClassName

GridBagLayout

Purpose

To lay out the components in the container.

Syntax

protected void ArrangeGrid(Container parent)

Parameters

parent

Container to be laid out.

Description

This protected method implements the layout policy of this layout manager and causes the components in the specified container to be laid out according to the constraints associated with each component.

Imports

import java.awt.GridBagLayout;

Returns

None.

Example

This method is a protected method in the GridBagLayout class and is used internally by the GridBagLayout implementation.

DumpConstraints(GridBagConstraints)

ClassName

GridBagLayout

Purpose

To print the values of the specified GridBagConstraints object.

Syntax

protected void DumpConstraints(GridBagConstraints c)

Parameters

c

GridBagConstraints object whose values are to be printed on the screen.

Description

This method is useful for debugging the implementation of the GridBagLayout layout manager. It simply prints the values of the variables of the specified GridBagConstraints object.

Imports

import java.awt.GridBagLayout;

Returns

None.

Example

This method is a protected method in the GridBagLayout class and is only used for debugging purposes by the GridBagLayout implementation.

DumpLayoutInfo(GridBagLayoutInfo)

ClassName

GridBagLayout

Purpose

To print debugging information contained in the layout parameters of the specified GridBagLayoutInfo object.

Syntax

protected void DumpLayoutInfo(GridBagLayoutInfo i)

Parameters

i

GridBagLayoutInfo object whose values are to be printed on the screen.

Description

The GridBagLayoutInfo class is used internally by the GridBagLayout class and it contains information about the layout (such as the number of cells horizontally and vertically in the layout, the largest minimum width in each row, and other parameters). This method simply prints these parameter values.

Imports

import java.awt.GridBagLayout;

Returns

None.

Example

This method is a protected method in the GridBagLayout class and is only used for debugging purposes by the GridBagLayout implementation.

getConstraints(Component)

ClassName

GridBagLayout

Purpose

To get the GridBagConstraints object associated with the specified component.

Syntax

public GridBagConstraints getConstraints(Component comp)

Parameters

comp

Component object whose GridBagConstraints should be retrieved.

Description

This method returns a copy of the GridBagConstraints object associated with the specified component.

Imports

import java.awt.GridBagLayout;

Returns

The return value of this method is a GridBagConstraints object.

See Also

The GridBagConstraints class

Example

Please refer to the documentation on the GridBagConstraints class in this chapter.

getLayoutDimensions()

ClassName

GridBagLayout

Purpose

To get the largest minimum width measurements of the components in each row and the largest minimum height measurements of the components in each column .

Syntax

public int [] [] getLayoutDimensions()

Parameters

None.

Description

This method returns the largest minimum width and height measurements of components in each row and column of the layout.

Imports

import java.awt.GridBagLayout;

Returns

This method returns a two-dimensional array of integers, where the widths are specified in the first row of integers and the heights are specified in the second row.

Example

Please refer to chapter project for an example.

GetLayoutInfo(Container, int)

ClassName

GridBagLayout

Purpose

To determine the GridBagLayoutInfo parameters for the components in the specified container.

Syntax

protected GridBagLayoutInfo GetLayoutInfo(Container parent, int sizeflag)

Parameters

parent

Container object to be laid out.

sizeflag

Specifies whether to use each componentsí preferredSize method or minimumSize method, to determine the size of each component, while laying out the container.

Description

The GridBagLayoutInfo class is used internally by the GridBagLayout class and it contains information about the layout (such as the number of cells horizontally and vertically in the layout, the largest minimum width in each row, and other parameters). This method determines these parameter values.

Imports

import java.awt.GridBagLayout;

Returns

This method returns a GridBagLayoutInfo object containing the parameters for the current layout configuration.

Example

This method is a protected method in the GridBagLayout class and is only used internally by the GridBagLayout implementation.

getLayoutOrigin()

ClassName

GridBagLayout

Purpose

To get the coordinates of the starting point of this layout.

Syntax

public Point getLayoutOrigin()

Parameters

None.

Description

This method returns the x and y coordinates of the origin of the layout.

Imports

import java.awt.GridBagLayout;

Returns

This method returns a Point object that specifies the origin of the layout.

Example

Please refer to chapter project for an example.

getLayoutWeights()

ClassName

GridBagLayout

Purpose

To get the weights along each row and column.

Syntax

public double [] [] getLayoutWeights()

Parameters

None.

Description

This method returns the weights along each row and column of the layout. Weights are used to specify how to distribute space among the components of a row or column. Weights play an important role in the resizing behavior of a component. If the component is weighted in the direction of the x axis (GridBagConstraints.weightx), then the component will expand horizontally, and the component will expand vertically if it is weighted in the direction of the y axis (GridBagConstraints.weighty).

Imports

import java.awt.GridBagLayout;

Returns

This method returns a two-dimensional array of double precision floating point numbers that specifies the weights of the components in each row and column.

See Also

The weight and weighty variables of the GridBagConstraints class

Example

Please refer to chapter project for an example.

GetMinSize(Container, GridBagLayoutInfo)

ClassName

GridBagLayout

Purpose

To determine the minimum dimensions for the layout.

Syntax

protected Dimension GetMinSize(Container parent, GridBagLayoutInfo i)

Parameters

parent

Container object to be laid out.

i

GridBagLayoutInfo object containing the parameters of the overall layout configuration.

Description

This method is used to calculate the minimum width and height measurements required of the layout. The minimum dimensions are calculated according to the following formulae:
Minimum width = (Left + Right insets of parent) + (sum of largest minimum widths in each column)
Minimum height = (Top + Bottom insets of parent) + (sum of largest minimum heights in each row)

Imports

import java.awt.GridBagLayout;

Returns

This method returns a Dimension object containing the minimum dimensions of the layout.

See Also

The minimumLayoutSize method of this class

Example

This method is a protected method in the GridBagLayout class and is only used internally by the GridBagLayout implementation.

layoutContainer(Container)

ClassName

GridBagLayout

Purpose

To lay out the specified container according to the constraints for each component.

Syntax

public void layoutContainer(Container parent)

Parameters

parent

Container object to be laid out.

Description

This method lays out the components in the container, using the GridBagConstraints object associated with each component as a guideline for laying out the components. Applications do not directly invoke this method. The layout method of the Container class results in a call to this method.

Imports

import java.awt.GridBagLayout;

Returns

None.

See Also

The LayoutManager interface; the Container class

Example

Please refer to chapter project for an example.

location(int, int)

ClassName

GridBagLayout

Purpose

To get the coordinates of the top left corner of the component where the specified point x, y lies.

Syntax

public Point location(int x, int y)

Parameters

x

The x coordinate of the point.

y

The y coordinate of the point.

Description

This method returns the location of the component containing the specified point.

Imports

import java.awt.GridBagLayout;

Returns

This method returns the coordinates of the component that contains the point specified by the given x and y values.

Example

Please refer to chapter project for an example

lookupConstraints(Component)

ClassName

GridBagLayout

Purpose

To get the GridBagConstraints object associated with the specified component.

Syntax

protected GridBagConstraints lookupConstraints(Component comp)

Parameters

comp

Component object whose GridBagConstraints should be retrieved.

Description

This method retrieves the GridBagConstraints object associated with the specified component. The object returned by this method is the actual constraints object used by the GridBagLayout layout manager, and hence, care should be taken if one is modifying the parameters of this GridBagConstraints object.

Imports

import java.awt.GridBagLayout;

Returns

This method returns a GridBagConstraints object containing the constraints used for laying out the specified component.

See Also

The GridBagConstraints class

Example

This method is a protected method in the GridBagLayout class and is only used internally by the GridBagLayout implementation.

minimumLayoutSize(Container)

ClassName

GridBagLayout

Purpose

To calculate the minimum size required to lay out the container, taking into account the components in the specified container.

Syntax

public Dimension minimumLayoutSize(Container parent)

Parameters

parent

Container that needs to be laid out.

Description

This method calculates and returns the minimum dimensions required by the GridBagLayout manager to lay out the components contained within the specified container.

Imports

import java.awt.GridBagLayout;

Returns

The return type of this method is Dimension. This return value contains the minimum height and width required to lay out the container in the specified panel.

See Also

The Container class; the LayoutManager interface

Example

This method can be invoked on a GridBagLayout object, similar to the manner in which it is invoked on the corresponding function in the FlowLayout class.

preferredLayoutSize(Container)

ClassName

GridBagLayout

Purpose

To calculate the preferred dimensions for this layout, taking into account the components in the specified container.

Syntax

public Dimension preferredLayoutSize(Container target)

Parameters

target

Container that needs to be laid out.

Description

This method computes the ideal width and height required by this layout. The values returned have no effect unless the program specifically enforces these dimensions.

Imports

import java.awt.GridBagLayout;

Returns

The return type of this method is Dimension. This return value contains the ideal height and width required to lay out the container in the specified panel.

See Also

The Container class, the LayoutManager interface

Example

This method can be invoked on a GridBagLayout object, similar to the manner in which it is invoked on the corresponding function in the FlowLayout class.

removeLayoutComponent(Component)

ClassName

GridBagLayout

Purpose

To remove the specified component from the layout.

Syntax

public void removeLayoutComponent(Component comp)

Parameters

comp

Component to be removed from the layout.

Description

This method is a dummy stub in the GridBagLayout class, as this layout manager doesnít need to maintain associations between components and areas on the display.

Imports

import java.awt.GridBagLayout;

Returns

None.

See Also

The Container class; the LayoutManager interface

Example

This method can be invoked on a GridBagLayout object, similar to the manner in which it is invoked on the corresponding function in the FlowLayout class.

setConstraints(Component, GridBagConstraints)

ClassName

GridBagLayout

Purpose

To apply the GridBagConstraints to the specified component.

Syntax

public void setConstraints(Component comp, GridBagConstraints constraints)

Parameters

comp

Component object that the constraints are to be applied to.

constraints

Constraints for the component.

Description

This method applies the constraints specified in the constraints parameter to the specified component. These constraints are used to determine the position and dimensions of the component.

Imports

import java.awt.GridBagLayout;

Returns

None.

See Also

The GridBagConstraints class

Example

Please refer to the chapter project.

toString()

ClassName

GridBagLayout

Purpose

To represent the values of the GridBagLayout object as a String.

Syntax

public String toString()

Parameters

None.

Description

As the parameters associated with each component may be many in number, this method just prints the classname of this object (java.awt.GridBagLayout)

Imports

import java.awt.GridBagLayout;

Returns

This method returns a String containing the name of the GridBagLayout object.

See Also

The toString method of the Object class

Example

This method can be invoked on a GridBagLayout object similar to the manner in which it is invoked on the corresponding function in the FlowLayout class.

GridBagConstraints

Purpose

To specify the constraints for laying out a component using the GridBagLayout class.

Syntax

public class GridBagConstraints extends Object implements Cloneable

Description

The public variables of this class are used to specify the constraints for laying out a component within a container that uses a GridBagLayout object as its layout manager. Every component within the container is associated with an instance of this class. The GridBagConstraints values specify how the component is laid out within the container. Figure 4-16 shows the inheritance hierarchy for the GridBagConstraints class.

PackageName

java.awt

Imports

import java.awt.GridBagConstraints;

Constructors

public GridBagConstraints()

Parameters

None.

Variables

The following are the public variables that can be accessed and modified directly from within an application.

public int anchor

The value of this variable specifies where in the display area the GridBagLayout class will anchor this component if its display area is larger than the component. The point in the display area where the component can be anchored can be specified using one of the following values:
GridBagConstraints.NORTH
GridBagConstraints.SOUTH
GridBagConstraints.EAST
GridBagConstraints.WEST
GridBagConstraints.NORTHEAST
GridBagConstraints.NORTHWEST
GridBagConstraints.SOUTHEAST
GridBagConstraints.SOUTHWEST
GridBagConstraints.CENTER
The default value is GridBagConstraints.CENTER.

public Insets insets

The top, bottom, left, and right padding to leave between the component and the edge of its display area.

public int ipadx

The number of pixels to pad on the left and right sides of the component. Twice this value is added when calculating the minimum size for this component.

public int ipady

The number of pixels to pad on the top and bottom sides of the component. Twice this value is added when calculating the minimum size for this component.

public int gridx

Row number of the cell that occupies the upper-left corner of the componentís display area. Setting this value to GridBagConstraints.RELATIVE instructs the GridBagLayout class to lay out this component to the right of the previously added component.

public int gridy

Column number of the cell at the upper-left corner of the display area. Setting this value to GridBagConstraints.RELATIVE instructs the GridBagLayout class to lay out this component just below the previously added component.

public int gridwidth

Width of the componentís display area expressed as a number of cells in a row. Setting this value to GridBagConstraints.REMAINDER instructs the GridBagLayout class that this component is the last in its row. Setting this value to GridBagConstraints.RELATIVE instructs the GridBagLayout class that this component is next to the last in its row. The default value for this variable is 1.

public int gridheight

Height of the componentís display area expressed as a number of cells in a column. Setting this value to GridBagConstraints.REMAINDER instructs the GridBagLayout class that this component is the last in its column. Setting this value to GridBagConstraints.RELATIVE instructs the GridBagLayout class that this component is next to the last in its column. The default value for this variable is 1.

public double weightx

Specifies whether or not the componentís width should increase if it needs to be resized. A value must be specified for at least one component in a row. The default value for this variable is 0.

public double weighty

Specifies whether or not the componentís height should increase if it needs to be resized. A value must be specified for at least one component in a column. The default value for this variable is 0.

Example

Refer to the section project for a detailed example that uses this class.


Figure 4-16  Inheritance hierarchy for the GridBagConstraints class

clone()

ClassName

GridBagConstraints

Purpose

To create a duplicate of this GridBagConstraints object

Syntax

public Object clone()

Parameters

None.

Description

A new instance of a GridBagConstraints object is created and an exact duplicate of this GridBagConstraints is made.

Imports

import java.awt.GridBagConstraints;

Returns

The return value is an Object that is a clone of this GridBagConstraints object. This return value must be cast as a GridBagConstraints object in order to use it as one.

See Also

The clone method of the Object class; the Cloneable interface

Example

The following sample code demonstrates the implementation of this method.

import java.awt.GridBagConstraints;

public class GBCTest

The Layout Demonstration

By now you are familiar with the layout manager interface and the API of Javaís ready-made layout managers. In the following project we will build an application that demonstrates the functionality of each of the layout managers discussed in this chapter. The project will help you visualize the effect that each of the layout managers: FlowLayout, GridLayout, BorderLayout, CardLayout, and GridBagLayout have on the appearance of the Container. Figure 4-17 shows a screenshot of this project.


Figure 4-17  The Layout Demonstration project

In this project, we present a simple user interface that allows people to see the impact of each particular layout manager by selecting from a list of choices. The appearance and position of the components on the screen change with the selection of a new layout. In this project, a set of buttons is created and these buttons are placed within a Panel using different layout techniques. The simple user interface lets you flip through different layout views. This project also demonstrates customizing a layout by specifying parameters (such as the alignment mode, the horizontal gap between components, and so on).

Assembling the Project

1.  Create and edit a file named LayoutDemo.java and use this file to enter the code for this project. First, ensure that the necessary Java modules are imported.

import java.awt.*;
import java.applet.Applet;

2.  Now create a panel containing buttons. The SlidePanel class does this. The buttons on this panel will be laid out using different layout managers. By passing a different layout manager as the argument to the methods of the SlidePanel class, we can create different layouts of the buttons created by the SlidePanel class. This is accomplished by associating a layout manager with this Panel. The buttons are added to different areas of the panel. The significance of these areas depends on the layout manager being used to lay out the buttons on the panel. A Label component at the bottom of the panel displays the parameters of the layout manager used to lay out the components on the panel.

class SlidePanel extends Panel

3.  The GridBagLayout is a complex layout manager that requires constraints to be associated with each component. Add this method to the SlidePanel class. It arranges the buttons on the SlidePanel using the GridBagLayout class. The actual assignment of constraints to buttons and adding them to the layout is implemented as three protected methods: makeFirstRow, makeSecondRow, and makeThirdRow. A Label component at the bottom of the panel displays the parameters of the layout manager used to lay out the components on the panel.

// use the GridBagLayout class to layout buttons
Panel gridBagSlide()

4.  Assign constraints such that three buttons are laid out on the first row. Assigning a value to weightx of the GridBagConstraints object ensures that the buttons will expand horizontally and occupy space along the row, if the window is resized.

protected void makeFirstRow(GridBagConstraints gc,
GridBagLayout gl, Panel pan)

5.  Create and lay out a button such that it occupies all the remaining space in a row. In addition, add a second button that occupies two rows.

protected void makeSecondRow(GridBagConstraints gc,
GridBagLayout gl, Panel pan)

6.  On the third row, set the constraints so that a button occupies the entire row.

protected void makeThirdRow(GridBagConstraints gc,
GridBagLayout gl, Panel pan)

7.  The main display needs to be able to display multiple views of the Panel of buttons, each view implementing a particular layout. The CardLayout layout manager is ideal for this task. Each view can be a card in the card layout. To display a layout, the card containing the view has to be made visible. In the constructor for the SlidePanel class, create new Panels of buttons and associate each with a different layout manager. The SlidePanel class is now complete.

SlidePanel()

8.  Now create the LayoutDemo class. For this class to run as an applet, it will have to extend the java.applet.Applet class. It maintains a reference to the card stack of panels and shuffles this card stack to display the various layout views. The display area that will contain the card stack of panels is positioned above the choice control with which you can change the layout being used to place the buttons on the screen. Using the Center and South areas of a BorderLayout accomplishes this in a snap. A Panel is used to neatly arrange the choice component and the layout description label. A Choice component, with the names of all the different layouts that can be viewed, is added to the Panel. This code is implemented in the init method of the LayoutDemo class. The following sample code is an example of what it takes to implement this portion of the project.

public class LayoutDemo extends Applet


All that remains to be implemented is a simple interface for the applet. Using this interface you can view the different layouts.

9.  The following event handler determines which of the controls was activated by the user and displays the corresponding card. The event handler brings the card, corresponding to the selected choice, to the top of the view stack.

public boolean action(Event evt, Object arg) else if ('First card'.equals(arg)) else if ('Last card'.equals(arg)) else if ('Next card'.equals(arg)) else if ('Previous card'.equals(arg))
return true;

10.  And now the final step of creating a main function, required to launch the application if it were executed as a stand-alone Java application. It creates a top-level Frame window and emulates the behavior of an applet, by invoking the init methods of the LayoutDemo class.

public static void main(String args[])


And we are done!

11.  Save the LayoutDemo.java file and compile the project by executing the following command:

javac LayoutDemo.java

12.  Now run the program by executing the following command:

java LayoutDemo

How It Works

The Layout Demonstration project used different layout managers to lay out the same set of buttons on the screen. The CardLayout layout manager was used to present the different layout views, one at a time, to the user. Panels and Frames were used as containers for components (such as Buttons and Labels). Choice components and buttons that initiated actions enabled the user to flip through the various views in the CardLayout. The ready-made layout managers that are in the Java AWT are sufficient for most applications. Choose the layout manager or windowing component most suited to your requirements. By nesting panels within panels, you can use different layout managers for different parts of your user interface.

Have fun in creating user interfaces for Java applications!

setMenuBar(MenuBar)

ClassName

Frame

Purpose

Sets the menu bar for this Frame to the specified MenuBar object

Syntax

public synchronized void setMenuBar(MenuBar mb)

Parameters

mb

The MenuBar object that represents the menu bar for this Frame

Description

This method specifies the menu bar to use on this Frame window.

Imports

import java.awt.Frame;

Returns

None.

See Also

The Image Class

Example

Refer to the examples in the MenuBar section of Chapter 6.






Politica de confidentialitate



DISTRIBUIE DOCUMENTUL

Comentarii


Vizualizari: 476
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2022 . All rights reserved

Distribuie URL

Adauga cod HTML in site