Adding Window Components

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, which is an instance method defined in the GBFrame class,

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


addLabel(text, row, column, width, height)


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);


  In this application, each widget except for the command button occupies a single column and a single row in the grid.  The command button occupies both columns in its row, because the programmer has specified its width as 2 columns.

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