Java How to Program习题_第十二章_GUI组件——第一部分(GUI Components: Part 1)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hpdlzu80100/article/details/86493722

这章习题,除了Optional和Making Difference以外,全做完了,剩下的有空可以做做!信心是有了!

Self-Review Exercises

12.1 Fill in the blanks in each of the following statements:

a) Method mouseMoved is called when the mouse is moved with no buttons pressed and an event listener is registered to handle the event.

b) Text that cannot be modified by the user is called uneditable (read-only) text.

c) A(n) layout manager arranges GUI components in a Container.

d) The add method for attaching GUI components is a method of class Container.

e) GUI is an acronym for Graphical User Inteface.

f) Method setLayout is used to specify the layout manager for a container.

g) A mouseDragged method call is preceded by a(n) mousePressed method call and followed by a(n) mouseReleased method call.

h) Class JOptionPane contains methods that display message dialogs and input dialogs.

i) An input dialog capable of receiving input from the user is displayed with method showInputDialog of class JOptionPane.

j) A dialog capable of displaying a message to the user is displayed with method showMessageDialog of class JOptionPane.

k) Both JTextFields and JTextAreas directly extend class JTextComponent.

12.2 Determine whether each statement is true or false. If false, explain why.

a) BorderLayout is the default layout manager for a JFrame’s content pane. (T)

b) When the mouse cursor is moved into the bounds of a GUI component, method mouseOver is called. (F)

Answer: Method mouseEntered is called.

c) A JPanel cannot be added to another JPanel. (F)

Answer: A JPanel can be added to another JPanel, because JPanel is an indirect subclass of Component. So, a JPanel is a Component. Any Component can be added to a Container.

d) In a BorderLayout, two buttons added to the NORTH region will be placed side by side. (F)

Answer: Only the last button added will be displayed. Remember that only one component should be added to each region in a BorderLayout.

e) A maximum of five components can be added to a BorderLayout. (T)

[Note: Panels containing multiple components can be added to each region.]

f) Inner classes are not allowed to access the members of the enclosing class. (F)

Answer: Inner classes have access to all members of the enclosing class declaration.

g) A JTextArea’s text is always read-only. (F)

Answer: JTextAreas are editable by default.

h) Class JTextArea is a direct subclass of class Component. (F)

Answer: JTextArea derives from class JTextComponent.

12.3 Find the error(s) in each of the following statements, and explain how to correct it (them):

a) buttonName = JButton("Caption");

b) JLabel aLabel, JLabel;

c) txtField = new JTextField(50, "Default Text");

d) setLayout(new BorderLayout());

button1 = new JButton("North Star");

button2 = new JButton("South Pole");

add(button1);

add(button2);

Exercises

12.4 Fill in the blanks in each of the following statements:

a) The JTextField class directly extends class JTextComponent.

b) Container method add attaches a GUI component to a container.

c) Method mouseReleased is called when a mouse button is released (without moving themouse).

d) The class ButtonGroup is used to create a group of JRadioButtons.

12.5 Determine whether each statement is true or false. If false, explain why.

a) Only one layout manager can be used per Container. (T)

b) GUI components can be added to a Container in any order in a BorderLayout. (T)

c) JRadioButtons provide a series of mutually exclusive options (i.e., only one can be true at a time). (T)

d) Graphics method setFont is used to set the font for text fields.

e) A JList displays a scrollbar if there are more items in the list than can be displayed. (F)

f) A Mouse object has a method called mouseDragged. (F)

12.6 Determine whether each statement is true or false. If false, explain why.

a) A JPanel is a JComponent. (T)

b) A JPanel is a Component. (T)

c) A JLabel is a Container. (F)

d) A JList is a JPanel. (F)

e) An AbstractButton is a JButton. (F)

f) A JTextField is an Object. (T)

g) ButtonGroup is a subclass of JComponent.

12.7 Find any errors in each of the following lines of code, and explain how to correct them.

a) import javax.swing.JFrame

b) panelObject.GridLayout(8, 8);

c) container.setLayout(new FlowLayout(FlowLayout.DEFAULT));

d) container.add(eastButton, EAST); face

12.8 Create the following GUI. You do not have to provide any functionality.

12.9 Create the following GUI. You do not have to provide any functionality.

12.10 Create the following GUI. You do not have to provide any functionality.

12.11 Create the following GUI. You do not have to provide any functionality.

12.12 (Temperature Conversion) Write a temperature-conversion application that converts from Fahrenheit to Celsius. The Fahrenheit temperature should be entered from the keyboard (via a JTextField). A JLabel should be used to display the converted temperature. Use the following formula for the conversion: Celsius = × (Fahrenheit 32)

12.13 (Temperature-Conversion Modification) Enhance the temperature-conversion application of Exercise 12.12 by adding the Kelvin temperature scale. The application should also allow the user to make conversions between any two scales. Use the following formula for the conversion between Kelvin and Celsius (in addition to the formula in Exercise 12.12): Kelvin = Celsius + 273.15

12.14 (Guess-the-Number Game) Write an application that plays “guess the number” as follows: Your application chooses the number to be guessed by selecting an integer at random in the range 1–1000. The application then displays the following in a label: I have a number between 1 and 1000. Can you guess my number? Please enter your first guess. A JTextField should be used to input the guess. As each guess is input, the background color should change to either red or blue. Red indicates that the user is getting “warmer,” and blue, “colder.” A JLabel should display either "Too High" or "Too Low" to help the user zero in. When the user gets the correct answer, "Correct!" should be displayed, and the JTextField used for input should be changed to be uneditable. A JButton should be provided to allow the user to play the game again. When the JButton is clicked, a new random number should be generated and the input JTextField changed to be editable.

12.15 (Displaying Events) It’s often useful to display the events that occur during the execution of an application. This can help you understand when the events occur and how they’re generated. Write an application that enables the user to generate and process every event discussed in this chapter. The application should provide methods from the ActionListener, ItemListener, ListSelectionListener, MouseListener, MouseMotionListener and KeyListener interfaces to display messages when the events occur. Use method toString to convert the event objects received in each event handler into Strings that can be displayed. Method toString creates a String containing all the information in the event object.

12.16 (GUI-Based Craps Game) Modify the application of Section 6.10 to provide a GUI that enables the user to click a JButton to roll the dice. The application should also display four JLabels and four JTextFields, with one JLabel for each JTextField. The JTextFields should be used to display the values of each die and the sum of the dice after each roll. The point should be displayed in the fourth JTextField when the user does not win or lose on the first roll and should continue to be displayed until the game is lost.

(Optional) GUI and Graphics Case Study Exercise: Expanding the Interface

12.17 (Interactive Drawing Application) In this exercise, you’ll implement a GUI application that uses the MyShape hierarchy from GUI and Graphics Case Study Exercise 10.2 to create an interactive drawing application. You’ll create two classes for the GUI and provide a test class that launches the application. The classes of the MyShape hierarchy require no additional changes.

The first class to create is a subclass of JPanel called DrawPanel, which represents the area on which the user draws the shapes. Class DrawPanel should have the following instance variables:

a) An array shapes of type MyShape that will store all the shapes the user draws.

b) An integer shapeCount that counts the number of shapes in the array.

c) An integer shapeType that determines the type of shape to draw.

d) A MyShape currentShape that represents the current shape the user is drawing.

e) A Color currentColor that represents the current drawing color.

f) A boolean filledShape that determines whether to draw a filled shape.

g) A JLabel statusLabel that represents the status bar.

The status bar will display the coordinates of the current mouse position. Class DrawPanel should also declare the following methods:

a) Overridden method paintComponent that draws the shapes in the array. Use instance variable shapeCount to determine how many shapes to draw. Method paintComponent should also call currentShape’s draw method, provided that currentShape is not null.

b) Set methods for the shapeType, currentColor and filledShape.

c) Method clearLastShape should clear the last shape drawn by decrementing instance variable shapeCount. Ensure that shapeCount is never less than zero.

d) Method clearDrawing should remove all the shapes in the current drawing by setting shapeCount to zero. Methods clearLastShape and clearDrawing should call repaint (inherited from JPanel) to refresh the drawing on the DrawPanel by indicating that the system should call method paintComponent. Class DrawPanel should also provide event handling to enable the user to draw with the mouse. Create a single inner class that both extends MouseAdapter and implements MouseMotion- Listener to handle all mouse events in one class. In the inner class, override method mousePressed so that it assigns currentShape a new shape of the type specified by shapeType and initializes both points to the mouse position. Next, override method mouseReleased to finish drawing the current shape and place it in the array. Set the second point of currentShape to the current mouse position and add currentShape to the array. Instance variable shapeCount determines the insertion index. Set currentShape to null and call method repaint to update the drawing with the new shape. Override method mouseMoved to set the text of the statusLabel so that it displays the mouse coordinates—this will update the label with the coordinates every time the user moves (but does not drag) the mouse within the DrawPanel. Next, override method mouseDragged so that it sets the second point of the currentShape to the current mouse position and calls method repaint. This will allow the user to see the shape while dragging the mouse. Also, update the JLabel in mouse- Dragged with the current position of the mouse. Create a constructor for DrawPanel that has a single JLabel parameter. In the constructor, initialize statusLabel with the value passed to the parameter. Also initialize array shapes with 100 entries, shapeCount to 0, shapeType to the value that represents a line, currentShape to null and currentColor to Color.BLACK. The constructor should then set the background color of the Draw- Panel to Color.WHITE and register the MouseListener and MouseMotionListener so the JPanel properly handles mouse events. Next, create a JFrame subclass called DrawFrame that provides a GUI that enables the user to control various aspects of drawing. For the layout of the DrawFrame, we recommend a BorderLay  out, with the components in the NORTH region, the main drawing panel in the CENTER region, and a status bar in the SOUTH region, as in Fig. 12.49. In the top panel, create the components listed below. Each component’s event handler should call the appropriate method in class DrawPanel. a) A button to undo the last shape drawn. b) A button to clear all shapes from the drawing. c) A combo box for selecting the color from the 13 predefined colors. d) A combo box for selecting the shape to draw. e) A checkbox that specifies whether a shape should be filled or unfilled. Declare and create the interface components in DrawFrame’s constructor. You’ll need to create the status bar JLabel before you create the DrawPanel, so you can pass the JLabel as an argument to DrawPanel’s constructor. Finally, create a test class that initializes and displays the DrawFrame to execute the application.

12.18 (GUI-Based Version of the ATM Case Study) Reimplement the Optional ATM Case Study of Chapters 33–34 as a GUI-based application. Use GUI components to approximate the ATM user interface shown in Fig. 33.1. For the cash dispenser and the deposit slot use JButtons labeled Remove Cash and Insert Envelope. This will enable the application to receive events indicating when the user takes the cash and inserts a deposit envelope, respectively.

Making a Difference 12.19 (Ecofont) Ecofont (www.ecofont.eu/ecofont_en.html)—developed by SPRANQ (a Netherlands- based company)—is a free, open-source computer font designed to reduce by as much as 20% the amount of ink used for printing, thus reducing also the number of ink cartridges used and the environmental impact of the manufacturing and shipping processes (using less energy, less fuel for shipping, and so on). The font, based on sans-serif Verdana, has small circular “holes” in the letters that are not visible in smaller sizes—such as the 9- or 10-point type frequently used. Download Ecofont, then install the font file Spranq_eco_sans_regular.ttf using the instructions from the Ecofont website. Next, develop a GUI-based program that allows you to type in a text string to be displayed in the Ecofont. Create Increase Font Size and Decrease Font Size buttons that allow you to scale up or down by one point at a time. Start with a default font size of 9 points. As you scale up, you’ll be able to see the holes in the letters more clearly. As you scale down, the holes will be less apparent. What is the smallest font size at which you begin to notice the holes?

12.20 (Typing Tutor: Tuning a Crucial Skill in the Computer Age) Typing quickly and correctly is an essential skill for working effectively with computers and the Internet. In this exercise, you’ll build a GUI application that can help users learn to “touch type” (i.e., type correctly without looking at the keyboard). The application should display a virtual keyboard (Fig. 12.50) and should allow the user to watch what he or she is typing on the screen without looking at the actual keyboard. Use JButtons to represent the keys. As the user presses each key, the application highlights the corresponding JButton on the GUI and adds the character to a JTextArea that shows what the user has typed so far. [Hint: To highlight a JButton, use its setBackground method to change its background color. When the key is released, reset its original background color. You can obtain the JButton’s original background color with the getBackground method before you change its color.] You can test your program by typing a pangram—a phrase that contains every letter of the alphabet at least once—such as “The quick brown fox jumped over a lazy dog.” You can find other pangrams on the web. To make the program more interesting you could monitor the user’s accuracy. You could have the user type specific phrases that you’ve prestored in your program and that you display on the screen above the virtual keyboard. You could keep track of how many keystrokes the user types correctly and how many are typed incorrectly. You could also keep track of which keys the user is having difficulty with and display a report showing those keys.

猜你喜欢

转载自blog.csdn.net/hpdlzu80100/article/details/86493722