Java Reference
In-Depth Information
addActionListener(
new
ActionListener ()
{
public void
actionPerformed(ActionEvent e)
{
text . setText( text . getText () . trim() + CalculatorButton .
super
.
getText () ) ;
}
}
);
}
}
}
Note that all the number and operation buttons act similarly and therefore they
belong to same
CalculatorButton
class. Examine the body of the constructor of the
CalculatorButton
class. The
super(name)
call creates the button. The action listener is
notified when the button is pressed. It responds by appending the text from the button to
the text field in the north. Note the strange syntax:
CalculatorButton.super.getText()
.
The expression
CalculatorButton.super
refers to the super class of the outer object (i.e.,
the JButton). On the button object, the
getText
method is called. Note that we could
have also used the simpler syntax
text.setText(text.getText().trim() + getText())
.
Since there is no
getText
method in the local anonymous class, a method with name
getText
is searched for in the outer object and its super objects.
Next, let us examine the action listener for the button
EVALUATE
.The
eval
method
from JavaScript is used to evaluate the value of the expression in the text field. Once the
expression is evaluated, it is placed in the top text field. Note that the call may create an
exception if the expression is not mathematically sound. In this case, we simply change the
text field to display the empty string.
12.6 Creating Text Areas with Scroll Bars
We will next create a poor man's Notepad. For starters, we need an area where the user
can type text. Such an area can be created by instantiating an object of type
JTextArea
.
The
JTextArea
class has an empty constructor that creates the text area and
the size is automatically set. An object of type text area can also be created as fol-
lows:
new JTextArea(20,30)
. This creates a text area that has 30 lines. The number
20 represents the approximate width of the text area in characters (i.e., one can fit
approximately 20 characters per line).
We will start by adding a text area to the center of the window. We will want this
area to display scroll bars when needed. In order to do so, we will create an instance of the
JScrollPane
class and add it to the window. The constructor of the class takes as input the
text area where the scroll bars should be added. Here is our initial version of the program.
import
java .awt .
;
import
javax . swing .
∗
;
∗
public class
Notepad
{
public static void
main(String [] args)
{
NotepadFrame f =
new
NotepadFrame () ;
f . setVisible(
true
);