Archive for January, 2008

Web server setup - Chapter 12 Graphical User Interface Components: Part 1

Friday, January 18th, 2008

Chapter 12 Graphical User Interface Components: Part 1 649 12.2 Swing Overview The classes that create the GUI components of Fig. 12.2 are part of the Swing GUI components from package javax.swing. These GUI components became standard in Java with the release of the Java 2 platform version 1.2. Most Swing components (as they are commonly called) are written, manipulated and displayed completely in Java (so-called pure Java components). The original GUI components from the Abstract Windowing Toolkit package java.awt (also called the AWT) are tied directly to the local platform s graphical user interface capabilities. When a Java program with an AWT GUI executes on different Java platforms, the program s GUI components display differently on each platform. Consider a program that displays an object of type Button (package java.awt). On a computer running the Microsoft Windows operating system, the Button will have the same look and feel as the buttons in other Windows applications. Similarly, on a computer running the Apple Macintosh operating system, the Button will have the same look and feel as the buttons in other Macintosh applications. In addition to the differences in appearance, sometimes the manner in which a user interacts with a particular AWT component differs between platforms. Together, the appearance and how the user interacts with the program are known as that program s look and feel. The Swing components allow the programmer to specify a uniform look and feel across all platforms. In addition, Swing enables programs to provide a custom look and feel for each platform or even to change the look and feel while the program is running. For example, a program could enable users to choose their preferred look and feel. Look-and-Feel Observation 12.2 Swing components are written in Java, so they provide a greater level of portability and flexibility than the original Java GUI components from package java.awt. Swing components are often referred to as lightweight components they are written completely in Java so they are not weighed down by the complex GUI capabilities of the platform on which they are used. AWT components (many of which parallel the Swing components) that are tied to the local platform are correspondingly called heavyweight components they rely on the local platform s windowing system to determine their functionality and their look and feel. Each heavyweight component has a peer (from package java.awt.peer) that is responsible for the interactions between the component and the local platform that display and manipulate the component. Several Swing components are still heavyweight components. In particular, subclasses of java.awt.Window (such as JFrame used in several previous chapters) that display windows on the screen and subclasses of java.applet.Applet (such as JApplet) still require direct interaction with the local windowing system. As such, heavyweight Swing GUI components are less flexible than many of the lightweight components we will demonstrate. Portability Tip 12.1 The look of a GUI defined with heavyweight GUI components from package java.awtmay vary across platforms. Heavyweight components tie into the local platform GUI, which varies from platform to platform. Figure 12.3 shows an inheritance hierarchy of the classes that define attributes and behaviors that are common to most Swing components. Each class is displayed with its Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

648 Graphical User (Free php web host) Interface Components: Part 1 Chapter

Thursday, January 17th, 2008

648 Graphical User Interface Components: Part 1 Chapter 12 In this chapter and the next, we demonstrate many GUI components that enable users to interact with your programs. GUIs are built from GUI components (sometimes called controls or widgets shorthand notation for window gadgets). A GUI component is an object with which the user interacts via the mouse, the keyboard or another form of input, such as voice recognition. Several common GUI components are listed in Figure 12.2. In the sections that follow, we discuss each of these GUI components in detail. In the next chapter, we discuss more advanced GUI components. menu menu barbutton text field Fig. 12.1A sample Netscape Navigator window with GUI components. 12. Component Description JLabel An area where uneditable text or icons can be displayed. JTextField An area in which the user inputs data from the keyboard. The area can also display information. JButton An area that triggers an event when clicked. JCheckBox A GUI component that is either selected or not selected. JComboBox A drop-down list of items from which the user can make a selection by click ing an item in the list or possibly by typing into the box. JList An area where a list of items is displayed from which the user can make a selection by clicking once on any element in the list. Double-clicking an element in the list generates an action event. Multiple elements can be selected. JPanel A container in which components can be placed. Fig. 12.2Some basic GUI components. 12. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 12 Graphical User Interface Components: Part 1 (Web site development)

Thursday, January 17th, 2008

Chapter 12 Graphical User Interface Components: Part 1 647 Outline 12.1 Introduction 12.2 Swing Overview 12.3 JLabel 12.4 Event-Handling Model 12.5 JTextField and JPasswordField 12.5.1 How Event Handling Works 12.6 JButton 12.7 JCheckBox and JRadioButton 12.8 JComboBox 12.10 Multiple-Selection Lists 12.11 Mouse Event Handling 12.12 Adapter Classes 12.13 Keyboard Event Handling 12.14 Layout Managers 12.14.1 FlowLayout 12.14.2 BorderLayout 12.14.3 GridLayout 12.15 Panels 12.16 (Optional Case Study) Thinking About Objects: Use Cases Summary Terminology Self-Review Exercises Answers to Self-Review Exercises Exercises 12.1 Introduction A graphical user interface (GUI) presents a pictorial interface to a program. A GUI (pronounced GOO-EE ) gives a program a distinctive look and feel. Providing different programs with a consistent set of intuitive user interface components provides users with a basic level of familiarity with each program before they ever use it. In turn, this reduces the time users require to learn a program and increases their ability to use the program in a productive manner. Look-and-Feel Observation 12.1 Consistent user interfaces enable a user to learn new applications faster. As an example of a GUI, Fig. 12.1 contains a Netscape Navigator window with some of its GUI components labeled. In the window, there is a menu bar containing menus (File, Edit, View etc.). Below the menu bar there is a set of buttons that each have a defined task in Netscape Navigator. To the right of the buttons there is a text field in which the user can type the name of the World Wide Web site to visit. The menus, buttons and text fields are part of Netscape Navigator s GUI. They enable you to interact with the Navigator program. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Adelphia web hosting - 12 Graphical User Interface Components: Part 1 Objectives

Wednesday, January 16th, 2008

12 Graphical User Interface Components: Part 1 Objectives To understand the design principles of graphical user interfaces (GUI). To be able to build graphical user interfaces. To understand the packages containing GUI components and event-handling classes and interfaces. To be able to create and manipulate buttons, labels, lists, text fields and panels. To understand mouse events and keyboard events. To understand and be able to use layout managers. the wisest prophets make sure of the event first. Horace Walpole Do you think I can listen all day to such stuff? Lewis Carroll Speak the affirmative; emphasize your choice by utter ignoring of all that you reject. Ralph Waldo Emerson You pays your money and you takes your choice. Punch Guess if you can, choose if you dare. Pierre Corneille All hope abandon, ye who enter here! Dante Alighieri Exit, pursued by a bear. William Shakespeare Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 11 Graphics and Java2D 645 (Dedicated web hosting) 11.25 Write

Tuesday, January 15th, 2008

Chapter 11 Graphics and Java2D 645 11.25 Write a graphical version of your solution to Exercise 6.37 the Towers of Hanoi. After studying Chapter 18, you will be able to implement a version of this exercise using Java s image, animation and audio capabilities. 11.26 Modify the die-rolling program of Fig. 7.8 so that it updates the counts for each side of the die after each roll. Convert the application into a windowed application (i.e., a subclass of JFrame) and use Graphicsmethod drawString to output the totals. 11.27 Modify your solution to Exercise 7.21 Turtle Graphics to add a graphical user interface using JTextFields and JButtons. Also, draw lines rather than drawing asterisks (*). When the turtle graphics program specifies a move, translate the number of positions into a number of pixels on the screen by multiplying the number of positions by 10 (or any value you choose). Implement the drawing with Java2D API features. 11.28 Produce a graphical version of the Knight s Tour problem (Exercises 7.22, 7.23 and 7.26). As each move is made, the appropriate cell of the chessboard should be updated with the proper move number. If the result of the program is a full tour or a closed tour, the program should display an appropriate message. If you would like, use class Timer (see Exercise 11.24) to help animate the Knight s Tour. Every second, the next move should be made. 11.29 Produce a graphical version of the Tortoise and the Hare simulation (Exercise 7.41). Simulate the mountain by drawing an arc that extends from the bottom-left of the window to the top-right of the window. The tortoise and the hare should race up the mountain. Implement the graphical output so the tortoise and the hare are actually printed on the arc every move. [Note: Extend the length of the race from 70 to 300 to allow yourself a larger graphics area.] 11.30 Produce a graphical version of the Maze Traversal problem (Exercises 7.38-7.40). Use the mazes you produced as guides for creating the graphical versions. While the maze is being solved, a small circle should be displayed in the maze indicating the current position. If you would like, use class Timer (see Exercise 11.24) to help animate the traversal of the maze. Every second, the next move should be made. 11.31 Produce a graphical version of the Bucket Sort (Exercise 7.28) that shows each value being placed into the appropriate bucket and eventually being copied back to the original array. 11.32 Write a program that uses method drawPolyline to draw a spiral. 11.33 Write a program that inputs four numbers and graphs the numbers as a pie chart. Use class Arc2D.Double and method fill of class Graphics2D to perform the drawing. Draw each piece of the pie in a separate color. 11.34 Write an applet that inputs four numbers and graphs the numbers as a bar graph. Use class Rectangle2D.Doubleand method fill of class Graphics2D to perform the drawing. Draw each bar in a different color. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

644 Graphics and Java2D Chapter 11 11.11 Write (My web server)

Monday, January 14th, 2008

644 Graphics and Java2D Chapter 11 11.11 Write a program that displays randomly generated triangles in different colors. Each triangle should be filled with a different color. Use class GeneralPath and method fill of class Graphics2D to draw the triangles. 11.12 Write a program that randomly draws characters in different font sizes and colors. 11.13 Write a program that draws an 8-by-8 grid. Use the drawLinemethod. 11.14 Modify your solution to Exercise 11.13 to draw the grid using instances of class Line2D.Doubleand method draw of class Graphics2D. 11.15 Write a program that draws a 10-by-10 grid. Use the drawRectmethod. 11.16 Modify your solution to Exercise 11.15 to draw the grid by using instances of class Rectangle2D.Double and method draw of class Graphics2D. 11.17 Write a program that draws a tetrahedron (a pyramid). Use class GeneralPathand method draw of class Graphics2D. 11.18 Write a program that draws a cube. Use class GeneralPath and method draw of class Graphics2D. 11.19 In Exercise 3.9, you wrote an applet that input the radius of a circle from the user and displayed the circle s diameter, circumference and area. Modify your solution to Exercise 3.9 to read a set of coordinates in addition to the radius. Then draw the circle and display the circle s diameter, circumference and area, using an Ellipse2D.Double object to represent the circle and method draw of class Graphics2D to display the circle. 11.20 Write an application that simulates a screen saver. The application should randomly draw lines using method drawLine of class Graphics. After drawing 100 lines, the application should clear itself and start drawing lines again. To allow the program to draw continuously, place a call to repaint as the last line in method paint. Do you notice any problems with this on your system? 11.21 Here is a peek ahead. Package javax.swing contains a class called Timer that is capable of calling method actionPerformed of interface ActionListener at a fixed time interval (specified in milliseconds). Modify your solution to Exercise 11.20 to remove the call to repaint from method paint. Define your class so it implements ActionListener. (The actionPerformed method should simply call repaint.) Define an instance variable of type Timer called timerin your class. In the constructor for your class, write the following statements: timer = new Timer( 1000, this ); timer.start(); This creates an instance of class Timer that will call this object s actionPerformedmethod every 1000 milliseconds (i.e., every second). 11.22 Modify your solution to Exercise 11.21 to enable the user to enter the number of random lines that should be drawn before the application clears itself and starts drawing lines again. Use a JText- Field to obtain the value. The user should be able to type a new number into the JTextFieldat any time during the program s execution. Use an inner class definition to perform event handling for the JTextField. 11.23 Modify your solution to Exercise 11.21 such that it uses random number generation to choose different shapes to display (use methods of class Graphics).] 11.24 Modify your solution to Exercise 11.23 to use classes and drawing capabilities of the Java2D API. For shapes such as rectangles and ellipses, draw them with randomly generated gradients (use class GradientPaint to generate the gradient). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Chapter 11 Graphics and Java2D 643 a) g.setFont(

Monday, January 14th, 2008

Chapter 11 Graphics and Java2D 643 a) g.setFont( “SansSerif” ); b) g.erase( x, y, w, h ); // clear rectangle at (x, y) c) Font f = new Font( “Serif”, Font.BOLDITALIC, 12 ); d) g.setColor( Color.Yellow ); // change color to yellow ANSWERS TO SELF-REVIEW EXERCISES 11.1 a) setStroke, Graphics2D. b) GradientPaint. c) drawLine. d) red, green, blue. e) points. f) TexturePaint. 11.2 a) False. The first two arguments specify the upper-left corner of the bounding rectangle. b) True. c) True. d) True. e) False. Font sizes are measured in points. f) False. The coordinate (0,0) corresponds to the upper-left corner of a GUI component on which drawing occurs. 11.3 a) The setFont method takes a Font object as an argument not a String. b) The Graphics class does not have an erase method. The clearRect method should be used. c) Font.BOLDITALIC is not a valid font style. To get a bold italic font, use Font.BOLD + Font.ITALIC. d) Yellow should begin with a lowercase letter: g.setColor( Color.yellow );. EXERCISES 11.4 Fill in the blanks in each of the following statements: a) Class of the Java2D API is used to define ovals. b) Methods drawand fill of class Graphics2D require an object of type as their argument. c) The three constants that specify font style are , and . d) Graphics2Dmethod sets the painting color for Java2D shapes. 11.5 State whether each of the following is true or false. If false, explain why. a) The drawPolygon method automatically connects the endpoints of the polygon. b) The drawLine method draws a line between two points. c) The fillArcmethod uses degrees to specify the angle. d) In the Java coordinate system, y values increase from top to bottom. e) The Graphics class inherits directly from class Object. f) The Graphics class is an abstract class. g) The Font class inherits directly from class Graphics. 11.6 Write a program that draws a series of eight concentric circles. The circles should be separated by 10 pixels. Use the drawOval method of class Graphics. 11.7 Write a program that draws a series of eight concentric circles. The circles should be separated by 10 pixels. Use the drawArc method. 11.8 Modify your solution to Exercise 11.6 to draw the ovals by using instances of class Ellipse2D.Doubleand method draw of class Graphics2D. 11.9 Write a program that draws lines of random lengths in random colors. 11.10 Modify your solution to Exercise 11.9 to draw random lines, in random colors and random line thicknesses. Use class Line2D.Double and method draw of class Graphics2D to draw the lines. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

642 Graphics and Java2D Chapter 11 getFont method (Cool web site)

Sunday, January 13th, 2008

642 Graphics and Java2D Chapter 11 getFont method pixel getFontList method point getFontMetricsmethod polygon getGreenmethod Polygon class getHeightmethod positive degrees getLeadingmethod Rectangle2D.Double class getName method repaint method getRedmethod RGB value getSize method rotatemethod getStylemethod RoundRectangle2D.Double class GradientPaint class SansSeriffont Graphics class Seriffont graphics context setColormethod graphics object setFont method Graphics2D class setPaintmethod isBoldmethod setStrokemethod isItalicmethod Shape interface isPlain method Stroke interface Java2D API SystemColor class leading TexturePaint class Line2D.Double class translatemethod lineTomethod updatemethod Monospaced font vertical component moveTomethod x-axis negative degrees x-coordinate Paint interface y-axis paintmethod y-coordinate SELF-REVIEW EXERCISES 11.1 Fill in the blanks in each of the following statements: a) In Java2D, method of class sets the characteristics of a line used to draw a shape. b) Class helps define the fill for a shape such that the fill gradually changes from one color to another. c) The method of class Graphics draws a line between two points. d) RGB is short for , and . e) Font sizes are measured in units called . f) Class helps define the fill for a shape using a pattern drawn in a Buff eredImage. 11.2 State whether each of the following is true or false. If false, explain why. a) The first two arguments of Graphicsmethod drawOval specify the center coordinate of the oval. b) In the Java coordinate system, x values increase from left to right. c) Method fillPolygon draws a solid polygon in the current color. d) Method drawArcallows negative angles. e) Method getSize returns the size of the current font in centimeters. f) Pixel coordinate (0, 0) is located at the exact center of the monitor. 11.3 Find the error(s) in each of the following and explain how to correct the error(s). Assume that g is a Graphics object. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Affordable web hosting - Chapter 11 Graphics and Java2D 641 Class BufferedImage

Saturday, January 12th, 2008

Chapter 11 Graphics and Java2D 641 Class BufferedImage can be used to produce images in color and gray scale. A TexturePaint object uses the image stored in its associated BufferedImage as the fill texture for a filled-in shape. The RoundRectangle2D.Double constructor receives six arguments specifying the rectangle s dimensions and the arc width and arc height used to determine the rounding of the corners. The Arc2D.Double constructor s first four arguments specify the upper-left x-coordinate, upper-left y-coordinate, width and height of the bounding rectangle for the arc. The fifth argument specifies the start angle. The sixth argument specifies the end angle. The last argument specifies the type of arc (Arc2D.PIE, Arc2D.CHORDor Arc2D.OPEN). The Line2D.Double constructor s arguments specify starting and ending line coordinates. A general path is a shape constructed from straight lines and complex curves represented with an object of class GeneralPath (package java.awt.geom). GeneralPath method moveTo specifies the first point in a general path. GeneralPath method lineTo draws a line to the next point in the general path. Each new call to lineTo draws a line from the previous point to the current point. GeneralPath method closePath draws a line from the last point to the point specified in the last call to moveTo. Graphics2Dmethod translate moves the drawing origin to a new location. All drawing operations now use that location as (0, 0). Graphics2Dmethod rotate to rotate the next that is displayed. Its argument specifies the rotation angle in radians (with 360 = 2p radians). TERMINOLOGY addPointmethod drawPolygon method angle drawPolylinemethod arc bounded by a rectangle drawRectmethod arc height drawRoundRectmethod arc sweeping through an angle Ellipse2D.Double class arc width event Arc2D.Double class event-driven process ascent fillmethod background color fill3DRectmethod baseline fillArc method bounding rectangle filled polygon BufferedImage class fillOvalmethod closed polygon fillPolygon method closePathmethod fillRectmethod Color class fillRoundRectmethod Component class font coordinate Font class coordinate system font metrics degree font name descent font style draw an arc FontMetrics class drawmethod GeneralPath class draw3DRectmethod getAscentmethod drawArc method getBlue method drawLinemethod getDescentmethod drawOvalmethod getFamilymethod Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

640 Graphics and Java2D Chapter 11 Methods (Web hosting company)

Saturday, January 12th, 2008

640 Graphics and Java2D Chapter 11 Methods draw3DRectand fill3DRect take five arguments specifying the top-left corner of the rectangle, the width and heightof the rectangle and whether the rectangle is raised (true) or lowered (false). Methods drawRoundRect and fillRoundRectdraw rectangles with rounded corners. Their first two arguments specify the upper-left corner, the third and fourth arguments specify the width and height, and the last two arguments arcWidth and arcHeight determine the horizontal and vertical diameters of the arcs used to represent the corners. Methods drawOval and fillOval take the same arguments the top-left coordinate and the width and the height of the bounding rectangle that contains the oval. An arc is a portion of an oval. Arcs sweep from a starting angle the number of degrees specified by their arc angle. The starting angle specifies where the arc begins and the arc angle specifies the total number of degrees through which the arc sweeps. Arcs that sweep counterclockwise are measured in positive degrees and arcs that sweep clockwise are measured in negative degrees. Methods drawArcand fillArctake the same arguments the top-left coordinate, the width and the height of the bounding rectangle that contains the arc and the startAngle and arc- Angle that define the sweep of the arc. Polygons are multisided shapes. Polylines are a series of connected points. One Polygon constructor receives an array containing the x-coordinate of each point, an array containing the y-coordinate of each point and the number of points in the polygon. One version of Graphicsmethod drawPolygon displays a Polygonobject. Another version receives an array containing the x-coordinate of each point, an array containing the y-coordinate of each point and the number of points in the polygon and displays the corresponding polygon. Graphics method drawPolyline displays a series of connected lines specified by its arguments (an array containing the x-coordinate of each point, an array containing the y-coordinate of each point and the number of points). Polygonmethod addPointadds pairs of x- and y-coordinates to a Polygon. The Java2D API provides advanced two-dimensional graphics capabilities for processing line art, text and images. To access the Graphics2D capabilities, downcast the Graphics reference passed to paint to a Graphics2d reference. Graphics2D method setPaint sets the Paint object that determines the color and texture for the shape to display. A Paint object is an object of any class that implements interface java.awt.Paint. The Paint object can be a Color or an instance of the Java2D API s GradientPaint, SystemColoror TexturePaint classes. Class GradientPaint draws a shape in a gradually changing color called a gradient. Graphics2D method fill draws a filled Shape object. The Shapeobject is an instance of any class that implements interface Shape. The Ellipse2D.Double constructor receives four arguments specifying the bounding rectangle for the ellipse to display. Graphics2D method setStroke sets the characteristics of the lines used to draw a shape. Method setStroke requires a Stroke object as its argument. The Stroke object is an instance of any class that implements interface Stroke, such as a BasicStroke. Graphics2D method draw draws a Shape object. The Shape object is an instance of any class that implements interface Shape. The Rectangle2D.Double constructor receives four arguments specifying the upper-left x- coordinate, upper-left y-coordinate, width and height of the rectangle. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01