Java Reference
In-Depth Information
implements the
interface
ActionListener
, we do not need to explicitly instantiate
a listener object. We can simply use the reference
this
as an argument to the method
addActionListener
to register the listener.
The following statements instantiate the 16
JButtons
, place them in the content
pane at the proper locations, and register the listener object:
int
x, y;
x = 10;
y = 40;
for
(
int
ind = 0; ind < 16; ind++)
{
button[ind] =
new
JButton(keys[ind]);
//instantiate the
//JButton and assign
//it a label
button[ind].addActionListener(
this
);
//register the
//listener object
button[ind].setSize(50,30);
//set the size
button[ind].setLocation(x, y);
//set the location
pane.add(button[ind]);
//place the button
//in the content pane
//determine the coordinates of the next JButton
x = x + 50;
if
((ind + 1) % 4 == 0)
{
x = 10;
y = y + 30;
}
}
The inputs to the program are integers, various operations, and the equal symbol.
The numbers are entered via the buttons whose labels are digits, and the operations
are specified via the buttons whose labels are operations. When the user presses the
button with the label
=
, the program displays the results. The user can also press the
button with the label
C
to clear the numbers.
Because Java accepts only strings as inputs in a GUI component, we need two
String
variables to store the number strings. Before performing the operation, the
strings will be converted to their numeric form.
To input numbers, the user presses various digit buttons, one at a time. For example,
to specify that a number is
235
, the user presses the buttons labeled
2
,
3
, and
5
in
sequence. After pressing each button, the number is displayed in the text field. Each
number is entered as a string and therefore concatenated with the previous string.
When the user presses an operation button, it indicates that the user is about to enter
the second number. Therefore, we use a
boolean
variable, which is set to
false
after the first number is input. We will need the following variables:
Search WWH ::
Custom Search