📄 ch5.htm
字号:
int graphMode;<BR> Color randomColors[];<BR> // This is the data for the display..<BR> GraphData gd;<BR> // Maximum scale of graph...<BR> int maxValue;<BR><BR> // Constructor just inits data...<BR> public GraphCanvas() {<BR> gd = null;<BR> // Store the random colors...<BR> randomColors = new Color[6];<BR> randomColors[0] = Color.yellow;<BR> randomColors[1] = Color.red;<BR> randomColors[2] = Color.green;<BR> randomColors[3] = Color.magenta;<BR> randomColors[4] = Color.cyan;<BR> randomColors[5] = Color.blue;<BR> }<BR> // Set up graphics display...<BR> void prepareNewGraph(GraphData gphData,int graphMode){<BR> // Store the data and stringvalues...<BR> gd = gphData;<BR> this.graphMode = graphMode;<BR> // First calculate maximumvalue of graph...<BR> maxValue = calculateMaxValue();<BR> }<BR><BR> // Calculate the maximum value of the graph...<BR> int calculateMaxValue() {<BR> double maximum = 0.0;<BR> double data;<BR> int temp,roundMax;<BR> // First get maximum figure...<BR> int length = gd.size();<BR> for (int i = 0; i < length;++i) {<BR> data = gd.getData(i);<BR> if (data> maximum)<BR> maximum= data;<BR> } // end for<BR> // Now round it up to nearestpower of 10<BR> roundMax = 1;<BR> for (temp = (int)maximum;temp> 0; temp /= 10)<BR> roundMax*= 10;<BR> return roundMax;<BR> }<BR><BR><BR> // Draw the graph...<BR> public synchronized void paint (Graphics g){<BR> if (gd == null)<BR> return;<BR> Dimension dm = size();<BR><BR> // Calculate margins...<BR> int height = g.getFontMetrics().getHeight();<BR> int ymargin = 3 * height;<BR> int xmargin = g.getFontMetrics().stringWidth("1112345.67");<BR> int length = gd.size();<BR><BR> // Select bottom-left origin<BR> Point origin = new Point(xmargin,dm.height- ymargin);<BR><BR> // Draw X-Axis line<BR> int endx = dm.width - xmargin;<BR> g.drawLine(origin.x,origin.y,endx,origin.y);<BR><BR> // Draw Y-Axis line<BR> g.drawLine(origin.x,ymargin,origin.x,origin.y);<BR><BR> // Calculate how headers arespread out...<BR> int yIncrement = (origin.y- ymargin)/10;<BR> int xIncrement = (endx - origin.x)/ (length + 1);<BR><BR> // Draw horizontal axis headers<BR> int i,x;<BR> int yMarkStart = origin.y+ height;<BR> int yTextStart = yMarkStart+ height;<BR> for (i = 1; i < (length+ 1); ++i) {<BR> // Drawmarker...<BR> x = origin.x+ (xIncrement * i);<BR> g.drawLine(x,yMarkStart,x,origin.y);<BR> // Printvalue header...<BR> g.drawString(gd.getHeading(i- 1),x,yTextStart);<BR> }<BR><BR> // Draw vertical axis headers...<BR> int y;<BR> int inset = g.getFontMetrics().charWidth('W');<BR> int xMarkStart = origin.x- inset;<BR> int xTextStart = inset;<BR> int dataIncrement = maxValue/ 10;<BR> String yHeader;<BR> for (i = 0; i <= 10; ++i){<BR> // Drawmarker...<BR> y = origin.y- (i * yIncrement);<BR> g.drawLine(xMarkStart,y,origin.x,y);<BR> // Printincrement header...<BR> yHeader= String.valueOf(dataIncrement * i);<BR> g.drawString(yHeader,xTextStart,y);<BR> }<BR><BR> // Call Graphic specific drawing..<BR> int vertLength = origin.y- ymargin;<BR> double dbLen = (double)randomColors.length;<BR> int index;<BR> int rectOffset = xIncrement/ 2; // For bar graphs...<BR> Point lastPt = null;<BR> for (i = 1; i < (length+ 1); ++i) {<BR> // Plotpoints, connecting points with lines...<BR> x = origin.x+ (xIncrement * i);<BR> y = origin.y- (int)((gd.getData(i - 1)/maxValue) * vertLength);<BR> // Randomizecolors...<BR> index =(int)(dbLen * Math.random());<BR> g.setColor(randomColors[index]);<BR> // If linegraph, draw connecting lines...<BR> if (graphMode== LINE_GRAPH) {<BR> if(lastPt != null)<BR> g.drawLine(lastPt.x,lastPt.y,x,y);<BR> lastPt= new Point(x,y);<BR> }<BR> // Otherwise,bar graph draw rectangle...<BR> else {<BR> g.fillRect(x- rectOffset,y,xIncrement,origin.y - y);<BR> }<BR> } // end for<BR> }<BR>}</TT></BLOCKQUOTE><HR><P>After the maximum value is determined, the graph is ready to bepainted. This is surprisingly easy. The first step is to get thedimensions of the canvas area and to figure where the bottom-leftorigin of the graph should be; this is where the vertical linethat marks the range of values and the horizontal line that providesthe column headers will meet. The margins allow room at the sidesand the bottom for displaying the range and column headers. Theseare calculated through the use of the FontMetrics class's <TT>getHeight()</TT>and <TT>stringWidth()</TT> methods.These margins make it easy to calculate the operations that follow.The next step is drawing the vertical and horizontal lines fromthe origin to the appropriate margin.<P>The column headers are next drawn underneath the horizontal line.The location of the headers is based on the length of the linedivided by the number of columns. The horizontal range of valuesis calculated similarly, except that the locations are based ondividing the maximum value by ten and incrementing accordingly.The range values and headers are drawn through the <TT>drawString()</TT>method. The nearby <TT>drawLine()</TT>methods are used to make a small line marker indicating the rangeor header position.<P>The last step is to plot the graph. This is done in a <TT>for</TT>loop that moves across each column of data. For each column, arandom color is chosen for the ensuing graph figure. This is doneby using the <TT>Math.random()</TT>method, which returns a number between 0.0 and 1.0. The coloris then set by calling the Graphics object's <TT>setColor()</TT>method. The data is then plotted based on its position in relationto the origin and the maximum value. If it is a line graph, aline is drawn from the endpoint of the last line drawn to thenew value; the <TT>drawLine()</TT>method is used to do this. If it is a bar graph, a rectangle isdrawn from the horizontal baseline to the plotted value with the<TT>fillRect()</TT> method of theGraphics class. Both the line and the interior of the bar rectanglewill be the color just set by the random procedure.<H2><A NAME="Summary"><FONT SIZE=5 COLOR=#FF0000>Summary</FONT></A></H2><P>This concludes the development of the spreadsheet applet. By goingthrough this part of the book, you have learned most of the fundamentaltechniques needed to use the AWT package. You have also been exposedto exception handling, as well as the underlying principles ofusing input/output streams.<P>The next step is to tie these techniques in with some of Java'smore advanced features, such as multithreading and sockets programming.With a good understanding of these new techniques, you can producea network-enabled applet ready for prime-time use on the Internet!<P><HR WIDTH="100%"></P></P></CENTER><P><HR WIDTH="100%"></P><!-- reference library footer #1--></CENTER><IMG SRC="/images/rule.gif" WIDTH="460" HEIGHT="5" VSPACE="5"ALT="Ruler image"><br><FONT SIZE="-1">Contact <a href="mailto:reference@developer.com">reference@developer.com</a> with questions or comments.<br><a href="/legal/">Copyright 1998</a> <a href="http://www.earthweb.com" target="_top">EarthWeb Inc.</a>, All rights reserved.<BR>PLEASE READ THE <a href="/reference/usage.html">ACCEPTABLE USAGE STATEMENT</a>.<BR>Copyright 1998 Macmillan Computer Publishing. All rights reserved.</FONT></BLOCKQUOTE><!--outer table--><TD VALIGN="TOP"><!--right side ads --><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCAD1.REF" alt="Click here for more info"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCAD1.REF" alt="Click here for more info" height="88" width="88" border="0"></a><P><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCAD2.REF" alt="Click here for more info"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCAD2.REF" alt="Click here for more info" height="88" width="88" border="0"></a><P></td></tr></table></BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -