Window components, or
widgets as they are sometimes called, are added to an application window by
calling specific methods within the application window class.
Each such method,
creates a widget with some default attributes and some attributes provided by the methodÕs arguments
places the widget in the windowÕs grid
returns the widget to the application for further access and manipulation
The methods and the
arguments used to add the widgets to the window of the tax calculator are shown
below.
Type of
Window component |
Method
to add it to the window |
JLabel
|
addLabel(text,
row, column, width, height)
|
JButton
|
addButton(text,
row, column, width, height)
|
DoubleField extends JTextField
|
addDoubleField(value,
row, column, width, height)
|
IntegerField extends JTextField
|
addIntegerField(value,
row, column, width, height)
|
Note that the
arguments to these methods include an initial
value to be displayed in the widget, as well the row and column where the
widget is to go in the windowÕs grid and the number of columns (width) and rows (height) that the widget will occupy.
The rows and columns in the grid are numbered from 1. Thus, the grid position (1, 1) would lie in the upper left corner of the window. The tax calculator windowÕs grid has five rows of two columns each, as shown here:
|
The next code segment,
from the tax calculator program, adds label, double field, and button widgets to
the window:
// Label and field for the income
JLabel incomeLabel = addLabel("Income", 1,1,1,1);
DoubleField incomeField = addDoubleField(0.0, 1,2,1,1);
// The command button
JButton computeButton = addButton("Compute", 4,1,2,1);
Along with a grid position
and extent, a widget has an alignment within its grid cell, when the cell area is
larger than the widget itself. The
default values of this attribute are to the upper left and the upper right for labels and entry fields, respectively, because a label is often placed to
the left of a field. A button is aligned in the center of its grid cell.
The double field also has a precision attribute allowing the programmer to specify the
number of places to display to the right of a numberÕs decimal point. The label
and field widgets have a font attribute. All of the window components have background and foreground color attributes. The roles of
these attributes and the manner in which you can adjust them will become clear in later examples.
Back to tutorial | Next topic: Responding to button events |