Java Reference
In-Depth Information
Use a
FlowLayout
with a
JTextArea
for the source text and a separate
JTextArea
for the translated text. Add a
JButton
with an event to perform the translation.
A sample application is shown next with the text translated to Pig Latin.
To parse the source text, note that you can use the
Scanner
class on a
String
. For
example the following code
Scanner scan =
new
Scanner("foo bar zot");
while
(scan.hasNext())
{
System.out.println(scan.next());
}
will output
foo
bar
zot
2. Design and code a Swing GUI for a two-player tic-tac-toe (noughts and crosses)
game on a 3
3 game board. The
JFrame
should use a
BorderLayout
with a
JLabel
in the NORTH region to display messages (e.g., who won the game), and
a
JPanel
in the CENTER region to display the game board. For the game board in
the
JPanel
, use a
GridLayout
manager with a 3
*
3 layout of
JButton
's in each
cell to display the game board. The button labels should initially be blank. When
a player clicks on an empty button, an appropriate “X” or “O” should be placed in
the label field of the button. If there is a winner (three in a row), then the program
should display the winner in the
JLabel
located at the top of the window. If all
nine cells have been filled without a winner, the program should indicate that there
is a tie.
3. Design and code a Swing GUI calculator. You can use Display 17.19 as a starting
point, but your calculator will be more sophisticated. Your calculator will have
two text fields that the user cannot change: One labeled
"Result"
will contain the
result of performing the operation, and the other labeled
"Operand"
will be for
the user to enter a number to be added, subtracted, and so forth from the
result. The user enters the number for the
"Operand"
text field by clicking buttons
labeled with the digits
0
through
9
and a decimal point, just as in a real calculator.
Allow the operations of addition, subtraction, multiplication, and division. Use a
GridLayout
manager to produce a button pad that looks similar to the keyboard
on a real calculator.
When the user clicks a button for an operation, the following occurs: the operation
is performed, the
"Result"
text field is updated, and the
"Operand"
text field is
cleared. Include a button labeled
"Reset"
that resets the
"Result"
to
0.0
. Also
include a button labeled
"Clear"
that resets the
"Operand"
text field so it is blank.
Hint:
Define an exception class named
DivisonByZeroException
. Have your
code throw and catch a
DivisonByZeroException
if the user attempts to “divide
by zero.” Your code will catch the
DivisonByZeroException
and output a suit-
able message to the
"Operand"
text field. The user may then enter a new substitute
*