⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch3.htm

📁 JAVA Developing Professional JavaApplets
💻 HTM
📖 第 1 页 / 共 5 页
字号:
</TD></TR><TR VALIGN=TOP><TD WIDTH=163><TT>gridx</TT>, <TT>gridy</TT> </TD><TD WIDTH=427>Specifies the upper-left display of the grid cell. A value of <TT>GridBagConstraints.RELATIVE</TT> indicates that the component is to be placed just right of or below the component just added before.</TD></TR><TR VALIGN=TOP><TD WIDTH=163><TT>Gridwidth</TT>, </TD><TD WIDTH=427>Indicates the number of grid cells in its display area. The </TD></TR><TR VALIGN=TOP><TD WIDTH=163><TT>gridheight</TT></TD><TD WIDTH=427><TT>GridBagConstraints.REMAINDER</TT> value specifies that it is the last cell it is the next to last cell in the row or column.in the row or column. <TT>GridBagConstraints.RELATIVE</TT> indicates that </TD></TR><TR VALIGN=TOP><TD WIDTH=163><TT>Fill</TT></TD><TD WIDTH=427>Indicates what to do if the display area is not filled. If this value is set to <TT>GridBagConstraints.BOTH</TT>, then it will fill up the display area.</TD></TR><TR VALIGN=TOP><TD WIDTH=163><TT>ipadx</TT>, <TT>ipady</TT></TD><TD WIDTH=427>Used to specify internal padding to add to the component's minimum size.</TD></TR><TR VALIGN=TOP><TD WIDTH=163><TT>Insets</TT></TD><TD WIDTH=427>Sets the external padding around the component's display area.</TD></TR><TR VALIGN=TOP><TD WIDTH=163><TT>anchor</TT></TD><TD WIDTH=427>A directional scheme to indicate where a component should go if it does not fill up the display area. The <TT>GridBagConstraints.CENTER</TT> variable is the default value.</TD></TR><TR VALIGN=TOP><TD WIDTH=163><TT>weightx</TT>, </TD><TD WIDTH=427>Determines space distribution. The default value of zero results in </TD></TR><TR VALIGN=TOP><TD WIDTH=163><TT>weighty </TT> </TD><TD WIDTH=427>the components clumping together in the middle of the display. Otherwise, the value indicates a weighting in relation to the other row and column components.</TD></TR></TABLE></CENTER><P><P>Look at the Java API documentation for more information aboutthese variables.<P>The spreadsheet project throughout this part of the book usesGridBagLayout. In particular, the frame initialization uses thisclass to set how the text field, spreadsheet canvas, and scrollbarsare positioned in relation to each other. Look at these examplesto get more ideas about how GridBagLayout works.<H4>CardLayout</H4><P>The CardLayout class allows the developer to flip through a seriesof displays. The flipping action of CardLayout is similar to HyperCardor other card-based programs. This card style of presentationdifferentiates CardLayout from the other layouts in that onlyone card of information is displayed at a time.<P>The typical way to use CardLayout is to tie it to a container,like a Panel. A series of cards can then be added to the container.Every time a component is added to a container that uses CardLayout,a new &quot;card&quot; is added. A variety of methods can be usedto flip through the cards. For example, the <TT>first()</TT>method goes to the first card in the deck, <TT>next()</TT>goes to the next card, <TT>show()</TT>goes to a card with a certain name, and so on.<P>Listing 3.4 provides the source code for a program that can beused to flip through a deck displaying different graphical images.It is similar to the first example in this chapter.<HR><BLOCKQUOTE><B>Listing 3.4. Creating an example using CardLayout.<BR></B></BLOCKQUOTE><BLOCKQUOTE><TT>import java.awt.*;<BR>import java.lang.*;<BR>import java.applet.*;<BR>// This class illustrates card layouts by drawing a <BR>different<BR>// shape for a variety of cards...<BR>public class CardLayoutExample extends <BR>java.applet.Applet&nbsp;&nbsp;{<BR>&nbsp;// Each card consists of a canvas that draws the name<BR>&nbsp;// of the card...<BR>&nbsp;Panel p;<BR>&nbsp;CardLayout panelLayout;<BR>&nbsp;int index = 0;<BR>&nbsp;int lastIndex;<BR>&nbsp;public void init() {<BR>&nbsp;&nbsp;String name;<BR>&nbsp;&nbsp;// Set up display area...<BR>&nbsp;&nbsp;resize(300,200);<BR>&nbsp;&nbsp;setLayout(new BorderLayout());<BR><BR>&nbsp;&nbsp;// Create the panel that uses CardLayout<BR>&nbsp;&nbsp;p = new Panel();<BR>&nbsp;&nbsp;panelLayout = new CardLayout();<BR>&nbsp;&nbsp;p.setLayout(panelLayout);<BR>&nbsp;&nbsp;add(&quot;Center&quot;,p);<BR><BR>&nbsp;&nbsp;// Add a canvas to each card<BR>&nbsp;&nbsp;// The name variable is the shape to display...<BR>CardLayoutDrawCanvas c; // Reuse these...<BR>&nbsp;&nbsp;// Add the rectangle...<BR>&nbsp;&nbsp;name = &quot;Rectangle&quot;;<BR>&nbsp;&nbsp;c = new CardLayoutDrawCanvas(name);<BR>&nbsp;&nbsp;p.add(name,c);<BR><BR><BR>&nbsp;&nbsp;// Add the oval display...<BR>&nbsp;&nbsp;name = &quot;Oval&quot;;<BR>&nbsp;&nbsp;c = new CardLayoutDrawCanvas(name);<BR>&nbsp;&nbsp;p.add(name,c);<BR><BR></TT>&nbsp;<TT>&nbsp;// Add the roundrectangle display...<BR>&nbsp;&nbsp;name = &quot;RoundRect&quot;;<BR>&nbsp;&nbsp;c = new CardLayoutDrawCanvas(name);<BR>&nbsp;&nbsp;p.add(name,c);<BR><BR>&nbsp;&nbsp;// Show the first card...<BR>&nbsp;&nbsp;index = 0;<BR>&nbsp;&nbsp;lastIndex = 2;<BR>&nbsp;&nbsp;panelLayout.first(p);<BR>&nbsp;}<BR><BR>&nbsp;// A mouse click takes you to the next card...<BR>&nbsp;public boolean mouseDown(Event ev, int x, int y) {<BR>&nbsp;&nbsp;// Go to the next card or to beginning<BR>&nbsp;&nbsp;if (index != lastIndex) {<BR>&nbsp;&nbsp;&nbsp;panelLayout.next(p);<BR></TT>&nbsp;<TT>&nbsp;&nbsp;++index;<BR>&nbsp;&nbsp;}<BR></TT>&nbsp;<TT>&nbsp;else {&nbsp;&nbsp;//Go to first card...<BR>&nbsp;&nbsp;&nbsp;panelLayout.first(p);<BR>&nbsp;&nbsp;&nbsp;index = 0;<BR>&nbsp;&nbsp;}<BR>&nbsp;&nbsp;return true;<BR>&nbsp;}<BR><BR>}<BR><BR>// This is a custom canvas that is used for drawing<BR>// text, a rectangle, or nothing...<BR>class CardLayoutDrawCanvas extends Canvas {<BR>&nbsp;String name;<BR>&nbsp;// Constructor - store the applet to get drawing <BR>info...<BR></TT>&nbsp;<TT>public CardLayoutDrawCanvas(Strings) {<BR>&nbsp;&nbsp;name = s;<BR>&nbsp;}<BR>&nbsp;// Draw the image per the choices in the applet...<BR>&nbsp;public synchronized void paint (Graphics g) {<BR>&nbsp;&nbsp;// Get the current size of the display area...<BR>&nbsp;&nbsp;Dimension dm = size();<BR>&nbsp;&nbsp;// Draw based on choice...<BR>&nbsp;&nbsp;// Calculate center coordinates....<BR>&nbsp;&nbsp;int x,y,width,height;<BR>&nbsp;&nbsp;x = dm.width/4;<BR>&nbsp;&nbsp;y = dm.height / 4;<BR>&nbsp;&nbsp;width = dm.width / 2;<BR>&nbsp;&nbsp;height = dm.height / 2;<BR>&nbsp;&nbsp;// Paint a rectangle in the center...<BR>&nbsp;&nbsp;if (name.compareTo(&quot;Rectangle&quot;) == 0) {<BR>&nbsp;&nbsp;&nbsp;// Draw the rectangle in the center with colors!<BR>&nbsp;&nbsp;&nbsp;g.setColor(Color.blue);<BR>&nbsp;&nbsp;&nbsp;g.drawRect(x,y,width,height);<BR>&nbsp;&nbsp;&nbsp;g.setColor(Color.yellow);<BR>&nbsp;&nbsp;&nbsp;g.fillRect(x + 1,y + 1,width - 2,height - 2);<BR>&nbsp;&nbsp;} // end if<BR>&nbsp;&nbsp;// Paint an oval in the center...<BR>&nbsp;&nbsp;if (name.compareTo(&quot;Oval&quot;) == 0) {<BR>&nbsp;&nbsp;&nbsp;// Draw the rectangle in the center with colors!<BR>&nbsp;&nbsp;&nbsp;g.setColor(Color.blue);<BR>&nbsp;&nbsp;&nbsp;g.drawOval(x,y,width,height);<BR>&nbsp;&nbsp;&nbsp;g.setColor(Color.yellow);<BR>&nbsp;&nbsp;&nbsp;g.fillOval(x + 1,y + 1,width - 2,height - 2);<BR>&nbsp;&nbsp;} // end if<BR>&nbsp;&nbsp;if (name.compareTo(&quot;RoundRect&quot;) == 0) {<BR>&nbsp;&nbsp;&nbsp;// Draw the rectangle in the center with colors!<BR>&nbsp;&nbsp;&nbsp;int rounding = dm.width / 8;<BR>&nbsp;&nbsp;&nbsp;g.setColor(Color.blue);<BR>&nbsp;&nbsp;&nbsp;g.drawRoundRect(x,y,width,height,rounding,rounding);<BR>&nbsp;&nbsp;&nbsp;g.setColor(Color.yellow);<BR>&nbsp;&nbsp;&nbsp;g.fillRoundRect(x + 1,y + 1,width - 2,height- 2,<BR>&nbsp;&nbsp;&nbsp;&nbsp; rounding,rounding);<BR>&nbsp;&nbsp;} // end if<BR>&nbsp;}<BR>}</TT></BLOCKQUOTE><HR><H3><A NAME="EventHandling">Event Handling</A></H3><P>Programs written for most GUI environments take actions basedon events initiated by the user or the system. If the user clicksthe mouse, a &quot;mouse click&quot; event is issued. If the programwants to handle the mouse click, it needs to insert some codeto trap for any mouse click event. The program may pass the eventon to a default handler if it doesn't want to handle the event.The default handler encapsulates an object's standard behavior.For example, when you click a button, it should reflect the actionby showing a pressing motion. This default behavior should occurregardless of whether the program processes the mouse click event.<P>As stated earlier, the visual controls the user interacts within the AWT environment are derived from the Component class. Acritical method of this class is <TT>handleEvent()</TT>,which is used to process incoming events and relay them to theappropriate handler methods. Any component that needs to managespecific events will need to override this method with its ownhandler.<P>In this chapter's initial example, the canvas object that drawsshapes and text was repainted every time the user clicked theDraw button. (See Figure 3.3 and Listing 3.1.) The program madethis happen by adding the following code to the applet class,Example1:<BLOCKQUOTE><TT>// Handle events that have occurred<BR>public boolean handleEvent(Event evt) {<BR>switch(evt.id) {<BR>&nbsp;// This can be handled<BR>&nbsp;case Event.ACTION_EVENT: {<BR>&nbsp;&nbsp;if(evt.target instanceof Button)&nbsp;&nbsp;&nbsp;&nbsp;{<BR>&nbsp;&nbsp;&nbsp;// Repaint canvas to use new choices...<BR>&nbsp;&nbsp;&nbsp;c.repaint();<BR>&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;// end if<BR>&nbsp;&nbsp;&nbsp;return false;<BR>&nbsp;}<BR>&nbsp;default:<BR></TT>&nbsp;<TT>&nbsp;return false;<BR>&nbsp;}<BR>}</TT></BLOCKQUOTE><P>This code overrides the default handler of the Applet class (whichis a subclass of Component). The sample applet would do very littleif this code had not been added. Even though the default handlerwas overridden, the code can still allow default behavior to occur.The return code from the method tells the parent of the componentwhat should happen next. If the method returns true, then theevent has been completely handled and should not be passed tothe parent. On the other hand, a false return value allows theevent to be passed on. The event handler of the component's superclasscan also be called through this expression:<BLOCKQUOTE><TT>return super.handleEvent(evt);</TT></BLOCKQUOTE><P>The <TT>handleEvent()</TT> methodtakes as its sole parameter an instance of the Event class. Thisclass encapsulates information about the event that occurred.The <TT>id</TT> integer variable ofthe class represents the type of event that occurred. The mostwidely captured event is the one with the <TT>id</TT><TT>ACTION_EVENT</TT>. Each classof component has a specific action tied to it. For example, theaction for a Button object is its selection, such as a mouse click.For TextField objects, the action is the entry of the Return keyin the text field.<P>Other types of frequently caught events are those prefixed by<TT>KEY_</TT> and <TT>MOUSE_</TT>,which represent keyboard and mouse events, respectively. Otherevents include scrollbar actions and window events, such as Minimizeor Destroy.<P>In the preceding code, the <TT>handleEvent()</TT>method traps for button selections. When the button is selected,an event with an <TT>ACTION_EVENT</TT>ID is generated. Recall, however, that this example also had aTextField. To differentiate the button selection from a text fieldReturn keystroke, the code needs to tell what class of objectissued the event. It does this by looking at the Event targetvariable. In the example's code, the program checks to see whetherthe target is a button by using the <TT>instanceOf</TT>operator.<P>Other information can be found in Event variables. An optionalargument, the <TT>arg</TT> variable,provides information specific to the Event, such as the Objectof an action. For mouse events, the <TT>x</TT>and <TT>y</TT> variables can be usedto get the mouse position. The key variable is used to determinewhich keystroke corresponds to a <TT>KEY_</TT>event.<P>The Component class also has helper methods that can be used ifthe user wants to manage events in a simpler manner than <TT>handleEvent()</TT>provides. These helper methods are actually called by <TT>handleEvent()</TT>.However, the overriding of <TT>handleEvent()</TT>is not required to use the helper methods.<P>In the CardLayout example, cards were flipped by overriding the<TT>mouseDown()</TT> method, whichwas declared as follows.<BLOCKQUOTE><TT>public boolean mouseDown(Event ev, intx, int y)</TT></BLOCKQUOTE><P>This is used to trap mouse clicks, passing the current locationof the mouse in the x and y parameters. This call actually beginsin the <TT>handleEvent()</TT> method,which traps for events of ID <TT>MOUSE_DOWN</TT>.When such events are issued, <TT>handleEvent()</TT>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -