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

这章习题,除了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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值