📄 ch3.htm
字号:
<TR VALIGN=TOP><TD WIDTH=511><BLOCKQUOTE>Button<BR>Canvas<BR>Checkbox<BR>CheckboxGroup<BR>Choice<BR>Label<BR>List<BR>Scrollbar<BR>TextComponent<BR>TextArea (extends TextComponent)<BR>TextField (extends TextComponent)</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>The Component hierarchy complements these primitive controls withclasses based on the Container class. Containers are used to holdComponent classes and other Containers. Panels, Windows, Dialogs,and Applets are all notable Container subclasses. The Containerclasses are presented in more detail shortly.<P>You can use the primitive controls in Table 3.1 to quickly producea functional applet. Figure 3.2 shows such an applet; with fivecomponents, it enables the user to choose what to display andwhen to display it. A choice between painting nothing, a rectangle,or text is offered. The class that does the drawing is a customsubclass of the Canvas Component called DrawCanvas, located inthe middle of the applet. At the bottom of the screen is a Panelwith Button and Choice objects. The Choice menu object lets theuser decide what is to be painted when the Button object is clicked(or when the applet repaints). A TextField object at the top ofthe screen is used to specify which text will be displayed, iftext is used.<P><A HREF="f3-2.gif" ><B>Figure 3.2 </B>: <I>Example with five companents</I></A><P>Listing 3.1 provides the code for this example. Although the appletis simple, it illustrates a lot of features. The <TT>init()</TT>portion of the applet class (called <TT>Example1</TT>)shows how easy it is to create and add classes to the applet display.The <TT>handleEvent()</TT> methodoverrides the default event handler and is used to trap buttonclicks. The code checks to see whether the action came from itsbutton. If so, it forces the DrawCanvas object to repaint. Theuser's selection in the Choice box will then be reflected.<P>The DrawCanvas class inherits the features of Canvas and addsits own custom functions to it. When it is drawn with the <TT>paint()</TT>method, the class queries the applet about the user's selectionsand paints accordingly. This <TT>paint()</TT>method can be issued either when the user clicks the button orwhen a certain region of the canvas needs to be redrawn. The <TT>paint()</TT>method is part of all Component classes. It must be overridden,as in the DrawCanvas class, if any custom drawing needs to bedone.<P>The <TT>paint()</TT> method takesas its sole parameter an instance of the Graphics class. Thisclass offers different methods that can be used to set the featuresof the area being drawn. For example, the DrawCanvas class usesthe <TT>drawString()</TT> method toput some text up on the drawing area. The <TT>drawRect()</TT>and <TT>fillRect()</TT> methods painta rectangle that draws a border rectangle and its interior, respectively.These rectangles are painted a color established by the <TT>setColor()</TT>method. Since the <TT>paint()</TT>method and the Graphics class are at the basis of drawing AWTimages, you will see more examples of these throughout the restof the book.<BR><HR><BLOCKQUOTE><B>Listing 3.1. An applet with five components.<BR></B></BLOCKQUOTE><BLOCKQUOTE><TT>import java.awt.*;<BR>import java.lang.*;<BR>import java.io.*;<BR>import java.applet.*;<BR><BR>// This program illustrates a simple applet with a <BR>TextField,<BR><BR>// Panel, Button, Choice menu, and Canvas.<BR>public class Example1 extends Applet {<BR>TextField tf;<BR>DrawCanvas c;<BR>Button drawBtn;<BR>Choice ch;<BR>// Add the Components to the screen...<BR>public void init() {<BR><BR> // Set up display area...<BR> resize(300,200);<BR> setLayout(new BorderLayout());<BR><BR> // Add the components...<BR> // Add the text at the top.<BR> tf = new TextField();<BR> add("North",tf);<BR><BR></TT> <TT>// Add the custom Canvasto the center<BR> c = new DrawCanvas(this);<BR> add("Center",c);<BR><BR></TT> <TT>// Create the panelwith button and choices at the <BR>bottom...<BR> Panel p = new Panel();<BR> drawBtn = new Button("Draw Choice Item");<BR> p.add(drawBtn);<BR> // Create the choice box and add the options...<BR> ch = new Choice();<BR> ch.addItem("Rectangle");<BR> ch.addItem("Empty");<BR> ch.addItem("Text");<BR> p.add(ch);<BR> add("South",p);<BR>}<BR><BR>// Handle events that have occurred<BR>public boolean handleEvent(Event evt) {<BR>switch(evt.id) {<BR></TT> <TT>// This can be handled<BR> case Event.ACTION_EVENT: {<BR> if(evt.target instanceof Button) {<BR> // Repaint canvas to use new choices...<BR> c.repaint();<BR> } // end if<BR> return false;<BR> }<BR></TT> <TT>default:<BR> return false;<BR> }<BR>}<BR><BR>// Return the current choice to display...<BR>public String getChoice() {<BR> return ch.getSelectedItem();<BR>}<BR><BR>// Return the text in the list box...<BR>public String getTextString() {<BR> return tf.getText();<BR>}<BR>}<BR><BR>// This is a custom canvas that is used for drawing<BR>// text, a rectangle, or nothing...<BR>class DrawCanvas extends Canvas {<BR>Example1 e1app;<BR> // Constructor - store the applet to get drawing <BR>info...<BR> public DrawCanvas(Example1 a) {<BR> e1app = a;<BR> }<BR></TT> <TT>// Draw the image perthe choices in the applet...<BR> public synchronized void paint (Graphics g) {<BR> // Get the current size of the display area...<BR> Dimension dm = size();<BR> // Draw based on choice...<BR> String s = e1app.getChoice();<BR> // Calculate center coordinates...<BR> int x,y,width,height;<BR> x = dm.width/4;<BR> y = dm.height / 4;<BR> width = dm.width / 2;<BR> height = dm.height / 2;<BR> // Paint a rectangle in the center...<BR> if (s.compareTo("Rectangle") == 0) {<BR> // Draw the rectangle in the center with colors!<BR> g.setColor(Color.blue);<BR> g.drawRect(x,y,width,height);<BR> g.setColor(Color.yellow);<BR> g.fillRect(x + 1,y + 1,width - 2,height - 2);<BR> } // end if<BR> // Get the text in the applet and display in the <BR>middle...<BR> if (s.compareTo("Text") == 0) {<BR> String displayText = e1app.getTextString();<BR> g.setColor(Color.red);<BR> g.drawString(displayText,x,y + (height/2));<BR> }<BR></TT> <TT>}<BR>}</TT></BLOCKQUOTE><HR><P>The other Component in this example is a Panel, which is a subclassof Container. In the example, the Panel contains the Button andChoice objects. Containers are good for managing a group of Componentsand have a special meaning in AWT regarding how an object is displayed.Containers function as a broker for how a component within itis presented. If a component's display coordinates are outsidethe region of a container, it is clipped. More importantly, Containersprovide a mechanism for <I>how</I> an object is presented, especiallyits size and position. This is closely tied to how Layouts work,discussed briefly in the following section.<P>One interesting aspect of AWT is that the Applet class is derivedfrom Panel. This may seem unusual at first; however, an Appletreally functions as a Container. Objects that do not fit withinits area are clipped in display, and if the Applet is destroyed,so are the objects within it. Given this, the Applet class canbe easily understood as simply a Panel with additional functionsthat tie it to the workings of the native browser.<P>The Window, Frame, and Dialog classes are also Containers thatfigure prominently. These are used to create objects that "popup" outside the space of the applet, giving a multidimensionalfeel to an otherwise "flat" Web page. These classeswill be discussed in more detail in the next chapter.<H3><A NAME="Layouts">Layouts</A></H3><P>For someone who has not seen Java applet code before, one questionthat might immediately come to mind from the previous exampleis: How does the program know where to position the Componentobjects on the screen? After all, there is no coordinate informationin the code. And what do code expressions like <TT>add("North",tf)</TT> mean?<P>The key to understanding the previous code and how AWT displayscomponents in general is a knowledge of layouts. Containers relyon layouts to give you a way to determine the size and positionof the components within it. Every container is tied to a singleinstance of a layout. The layout that a container uses is eitherset by default or through programming. In Listing 3.1, the layoutof the Applet object, Example1, is set to an instance of the BorderLayoutclass by the line:<BLOCKQUOTE><TT>setLayout(new BorderLayout());</TT></BLOCKQUOTE><P>Since the Panel class is also a container, it too has a layout.The default class, FlowLayout, is used in the example.<P>Layouts are an important part of AWT because they take care ofa major issue in Java: portability. Although the language portionof Java takes care of software portability concerns, it cannot,by nature, take care of visual portability issues. Namely, howcan Java guarantee that an applet developed on a specific GUI(such as Windows 95) and on a specific monitor resolution (suchas VGA) have a proper look and feel on other platforms? The AWTpackage was designed to solve this problem. By providing a levelof abstraction above the native GUI, it can hide the specificsof the underlying environment from the developer. Layouts arekey elements of the visual part of the abstraction mechanism.By taking control of the sizing and positioning of components,layouts free the developer from having to worry about how to writean applet that looks good on the variety of monitor resolutionsin the field. Layouts dynamically calculate how to present a componentby looking at the native display-coordinate system at runtime;the sizing and positioning of the components is based on thisruntime information.<P>All layouts are derived from the LayoutManager interface, whichspecifies how a layout needs to function. AWT provides five classes(described in the following sections) that set up the LayoutManagerinterface. This range of layouts allows the developer to choosethe appropriate layout manager for the requirements at hand; ifthese choices aren't enough, a new class can be written. In fact,Java developers have already created several custom layout classes.Various incarnations of a RelativeLayout class have been createdthat lets you state where components go in relation to each other.By navigating the Java home pages on the Internet, you might finda layout class that better fits your development needs. Some ofthe entry points to Java on the Internet are mentioned in thisbook's Introduction.<H4>Border Layout</H4><P>In Listing 3.1, the applet specifies adding new components throughan unusual scheme that uses such terms as "North" and"South". This scheme reflects how the BorderLayout classworks. In the example, BorderLayout is tied to the Example1 appletclass when the <TT>setLayout()</TT>method is invoked. This method indicates that the Example1 object,which is an instance of Container, is tied to the BorderLayoutobject. When a Container uses BorderLayout, a Component is addedthrough a command of this form:<BLOCKQUOTE><TT>add(String direction, Component);</TT></BLOCKQUOTE><P>Direction is one of the following Strings: <TT>"North"</TT>,<TT>"South"</TT>, <TT>"East"</TT>,<TT>"West"</TT>, and <TT>"Center"</TT>.In short, the BorderLayout class uses a directional scheme toposition a component based on one of the five direction strings.A component set to the <TT>"North"</TT>direction is set to the top of the container, one that is setto <TT>"South"</TT> is positionedat the bottom, and so forth. The size of the components is determinedby other runtime information, such as the size of the container(usually set by the <TT>resize()</TT>method) and the attributes of the displayed component. The defaultbehavior of BorderLayout gives the component set to the <TT>"Center"</TT>direction any space not used by the other components. In Listing3.1, the Example1 applet dimensions are set to 300<FONT FACE="Symbol">¥</FONT>200pixels. The TextField and Panel objects are relatively small and
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -