Make certain that every field, label, and button follows the three basic steps: declare a variable, instantiate an object, and add it to the pane.. Once you have declared the button acti
Trang 1420 | Event-Driven Input and Output
Table 8.1 Test Plan for the Calculator Application
Table 8.1 shows a partial test plan for the Calculator application.The first test case assumes that the calculator has an initial value of 0.0 Successive test cases use the preceding re-sult as one of the two operands for a calculation To be more thorough, we should check that the application properly handles the closing of the window, and we should include both negative and positive values
Testing and Debugging Hints
1. Remember to label each input field with a prompting message
2. Make certain that every field, label, and button follows the three basic steps: declare a variable, instantiate an object, and add it to the pane
3. Remember to specify a layout manager for a pane or panel
4. The value in a TextField is a string If you need to input a number, you must use getText to input the string, and then convert the string to a number using methods such as Integer.parseInt and Double.parseDouble Applying these methods to a nonnumeric value causes the application to halt with an error
message such as Number Format Exception.
5. A button event listener declaration must follow the pattern of headings speci-fied by the ActionListener interface You can choose the name of the class, and its modifiers, but the rest of the class heading and the method signature must appear as shown in the examples in this book
6. Once you have declared the button action listener class, you must perform three steps to register the event listener: declare a variable of that class, instantiate an object of the class and assign its address to the variable, and register the listener by calling the button’s addActionListener method with the variable as its argument
7. Confirm that every part of an event loop is present, especially the exit condi-tion
Trang 2Graphical user interfaces (GUIs) provide more convenient and intuitive input for
users However, they also take more programming effort than the simple
line-oriented I/O that we’ve used in the past Java is one of the first widely used
languages to offer extensive support for GUI programming
The basic window object is a JFrame; it provides a content pane in the form of a
Containerobject that is returned by the getContentPane instance method We add user
in-terface objects to the content pane with the add method, and we remove them with the
removemethod As part of creating a JFrame, we must specify its default closing operation,
its size, and the layout manager to use for its content pane We use setVisible(true)to
make the frame appear on the screen and dispose() to remove the frame
Objects that we can place into a content pane include a JLabel, JTextField, and
JButton We can change the contents of a JLabel or JTextField with setText, and we
can retrieve the String value of a JTextField with getText A JPanel is another class,
with similarities to a content pane, that we can use to preassemble groups of
interface elements We can then add the whole JPanel as a unit to the content pane
of a JFrame, so that the group of elements appears together
We must register an event listener with an event source, such as a button, to
han-dle events from the source The event listener is registered with a call to
addActionListener An event handler is a method in a class definition that follows the
specification of the ActionListener interface
Event loops provide an implicit way of repeating actions in event-driven
applica-tions We must check that an event loop is designed properly and that all of its
aspects are implemented correctly
When a user interface includes multiple buttons, we can use the string associated
with each button to determine which one was clicked The event handler is passed
an ActionEvent value as a parameter, and we call its associated value-returning
instance method, getActionCommand, to retrieve the string associated with the button
Quick Check
1. What contains a content pane, and what does a content pane contain? (pp
376–380)
2. Where is an event sent when a user clicks a button with the mouse? (pp 385–393)
3. Where does updating of the process within an event loop occur? (pp 393–394)
4. What is the handler method to which button events are sent? (pp 385–393)
5. Write statements that declare a private JTextFieldvariable called dataField,
in-stantiate a corresponding object, and add it to a content pane called outPane
(pp 394–398)
6. Write a statement that adds a label with the message"Quick Check"to outPane
(pp 376–380)
Trang 37. When a dialog involves processing input from a field after a button has been clicked, what part of the code is responsible for reading the field and
processing it? (pp 394–396)
8. How do you register an event listener with a button? (pp 387–390)
9. What Java interface does an event listener implement, and in what package is the interface found? (pp 387–390)
10.What are the parts of an event loop? (pp 393–394)
11.Which method provides the string that we use to identify the source of an event? (pp 409–411)
Answers
1 A JFrame contains a content pane and the content pane contains user interface elements 2 The button event handler 3 In the user’s actions and in the event handler 4 actionPerformed
dataField = new JTextField( 10 );
outPane.add(dataField);
6 outPane.add(new JLabel( "Quick Check")); 7.The event handler 8 With the addActionListener method
9 ActionListener is found in java.awt.event 10 Initialization of the loop exit condition and the process, loop entry, exit condition update, process update, and exit 11 getActionCommand
Exam Preparation Exercises
1. If a and b are intvariables with a = 5 and b = 2, what output does each of the fol-lowing statements produce?
a outPane.add(new JLabel("a = " + a + "b = " + b));
b outPane.add(new JLabel("Sum:"+ a + b));
c outPane.add(new JLabel("Sum: "+ a + b));
d outPane.add(new JLabel(a / b + " feet"));
2. What does the following application display?
import java.awt.*;
import javax.swing.*;
public class ExamPrep {
public static void main(String[] args) {
JFrame out;
Container outPane;
final int LBS = 10; int price;
int cost;
char ch;
out = new JFrame();
Trang 4outPane = out.getContentPane();
out.setSize(300, 200);
out.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
outPane.setLayout(new GridLayout(0 1));
price = 30;
cost = price * LBS;
ch = 'A';
outPane.add(new JLabel("Cost is "));
outPane.add(new JLabel("" + cost));
outPane.add(new JLabel("Price is " + price + "Cost is " + cost));
outPane.add(new JLabel("Grade " + ch + " costs "));
outPane.add(new JLabel("" + cost));
out.setVisible(true);
}
}
3. To use each of the following statements, a Java application must importwhich
package(s)?
a outPane.add(new JLabel("x"));
b. private static class ButtonHandler implements ActionListener
c outPane.setLayout(new GridLayout(0, 2));
4. Given the statements
String heading;
String str;
heading = "Exam Preparation Exercises";
what is the output of each of the following code segments?
a outPane.add(new JLabel(""+ heading.length()));
b outPane.add(new JLabel(heading.substring(6, 16)));
c outPane.add(new JLabel(""+ heading.indexOf("Ex")));
5. Name three kinds of objects that can be contained in the content pane of a
JFrameobject
6. What are the steps in adding a data entry field to the content pane of a JFrame
object in Java?
7. What determines the amount of information in a prompt?
8. (True or False?) A JPanel can hold just one user interface element
Trang 59. Do we have to get a content pane from a JPanel as we do with a JFrame?
10. What method would you use to change the value displayed in a JTextField object?
11.When giving a value to a label with new, what is passed to the constructor?
12.What method do you use to change the text within an existing label?
13.What happens if you forget to include the statement dataFrame.setVisible(true);?
14.What are the three steps needed to add a button to a content pane?
15.What are the three parts of registering an event listener?
16. What happens when a user clicks a button but no listener is registered for the event?
17.How are normal classes and classes that implement the ActionListener interface different?
18 actionPerformedtakes one argument of a Java class What is the name of the class?
19.What are the parts of an event loop?
20.Why do you not have to write an event handler for window closing?
21.How do you associate a string with a button event?
22.Describe the two ways that multiple buttons can be distinguished
Programming Warm-Up Exercises
1 a. Declare a button variable called stop
b. Instantiate a button object, labeling it “Stop”, and assign its address to stop
c. Declare a button listener variable and instantiate a button listener object
d. Register the button listener with the button
e. Add the button to the content pane dataPane
f. Write the statements to declare a listener class
2. Provide a user interface with two buttons, Enter and Quit
a. Write the statements that declare variables for the buttons and a single listener
b. Write the statements that instantiate the buttons and the listener
c. Write the statements that add the buttons to the content pane
d. Write the statements that register the listener with the buttons
e. Write the statement that accesses a button’s name from within an event han-dler
f. Code a class that implements ActionListener When each button is clicked, display its name on the screen
Trang 6LIMITED WARRANTY The Publisher warrants that the Software media will be free from physical defects in mate-rials and workmanship for a period of ninety (90) days from the date of receipt Any implied warranties on the Software media are limited to ninety (90) days Some states/jurisdictions
do not allow limitations on duration of an implied warranty, so the above limitation may not apply to you
The Publisher’s, Borland’s, and the Publisher’s or Borland’s suppliers’ entire liability and your exclusive remedy shall be, at the Publisher’s or Borland’s option, either (a) return of the price paid, or (b) repair or replacement of the Software media that does not meet the Limited Warranty and which is returned to the Publisher with a copy of your receipt This Limited Warranty is void if failure of the Software has resulted from accident, abuse, or misapplica-tion Any replacement Software will be warranted for the remainder of the original warranty
period or thirty (30) days, whichever is longer Outside the United States, neither these
reme-dies nor any product support services offered are available without proof of purchase from
an authorized non-U.S source.
TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW,THE PUBLISHER, INPRISE, AND THE PUBLISHER’S OR BORLAND’S SUPPLIERS DISCLAIM ALL OTHER WARRANTIES AND CON-DITIONS, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WAR-RANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND NON-INFRINGEMENT, WITH REGARD TO THE SOFTWARE, AND THE PROVISION OF OR FAIL-URE TO PROVIDE SUPPORT SERVICES.THIS LIMITED WARRANTY GIVES YOU SPECIFIC LEGAL RIGHTS YOU MAY HAVE OTHERS, WHICH VARY FROM STATE/JURISDICTION TO STATE/JU-RISDICTION
LIMITATION OF LIABILITY
TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL THE PUB-LISHER, INPRISE, OR THE PUBLISHER’S OR INPRISE’S SUPPLIERS BE LIABLE FOR ANY SPE-CIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUP-TION, LOSS OF BUSINESS INFORMAINTERRUP-TION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT
OF THE USE OF OR INABILITY TO USE THE SOFTWARE PRODUCT OR THE PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES, EVEN IF INPRISE HAS BEEN ADVISED OF THE POS-SIBILITY OF SUCH DAMAGES IN ANY CASE, INPRISE’S ENTIRE LIABILITY UNDER ANY PRO-VISION OF THIS LICENSE AGREEMENT SHALL BE LIMITED TO THE GREATER OF THE AMOUNT ACTUALLY PAID BY YOU FOR THE SOFTWARE PRODUCT OR U.S $25 BECAUSE SOME STATES AND JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY, THE ABOVE LIMITATION MAY NOT APPLY TO YOU
HIGH RISK ACTIVITIES The Software is not fault-tolerant and is not designed, manufactured or intended for use or resale as on-line control equipment in hazardous environments requiring fail-safe per-formance, such as in the operation of nuclear facilities, aircraft navigation or
Trang 7communica-tion systems, air traffic control, direct life support machines, or weapons systems, in which
the failure of the Software could lead directly to death, personal injury, or severe physical or
environmental damage (“High Risk Activities”) The Publisher, Borland, and their suppliers
specifically disclaim any express or implied warranty of fitness for High Risk Activities
U.S GOVERNMENT RESTRICTED RIGHTS
The Software and documentation are provided with RESTRICTED RIGHTS Use, duplication,
or disclosure by the Government is subject to restrictions as set forth in subparagraphs
(c)(1)(ii) of the Rights in Technical Data and Computer Software clause at DFARS 252.227-7013
or subparagraphs (c)(1) and (2) of the Commercial Computer Software-Restricted Rights at
48 CFR 52.227-19, as applicable
GENERAL PROVISIONS
This License Agreement may only be modified in writing signed by you and an authorized
officer of Borland If any provision of this License Agreement is found void or unenforceable,
the remainder will remain valid and enforceable according to its terms If any remedy
pro-vided is determined to have failed for its essential purpose, all limitations of liability and
ex-clusions of damages set forth in the Limited Warranty shall remain in effect
This License Agreement shall be construed, interpreted and governed by the laws of the
State of California, U.S.A This License Agreement gives you specific legal rights; you may have
others which vary from state to state and from country to country Borland reserves all
rights not specifically granted in this License Agreement