Java Reference
In-Depth Information
fields. Note the two text fields need to be declared as
final
.Iftheywerenot
final
,then
they could not be accessed from the anonymous local class that inherits from the class
ActionListener
.
12.5 Grid Layout
We will next build a simple calculator. Figure 12.3 shows what our calculator will look
like. We will create three panels in the window: in the north, south, and center. The panel
in the middle will use the
grid layout
.
Whenever components need to be placed in a grid, one can use the grid layout.
When adding the components to a grid layout, the rows are filled from left to right and
from top to bottom. In other words, the first row is filled first and so on. The call to
the constructor
new GridLayout(3,5)
will create a 3x5 grid (3 rows and 5 columns).
Alternatively, the call
new GridLayout(2,4,3,6)
will generate a grid with 2 rows, 4
columns, a 3-pixel horizontal gap, and a 6-pixel vertical gap between the components.
For the calculator application, we will create a 4x4 grid in the center. Our calculator
will have very simple behavior. When the
CLEAR
button is pressed, the text field in the top
will be cleared. Alternatively, when the
EVALUATE
button is pressed, the expression in the
text field will be evaluated and its value will be displayed in the text field. Since computing
arithmetic expressions is beyond the scope of this topic, we will use the JavaScript function
eval
to evaluate an expression. Note that
JavaScript
is a programming language that is
different from Java. However, there is a mechanism for calling
JavaScript
functions from
Java. The complete code for the calculator program follows.
import
java .awt .
∗
;
import
java .awt. event .
∗
;
import
javax . swing .
∗
;
import
javax . script .
∗
;
public class
Calculator
{
FIGURE 12.3:
Calculator program.