<< Chapter < Page Chapter >> Page >

Listing 21 . Source code for the program named StringArt01.

/*StringArt01.java Copyright 2008, R.G.BaldwinRevised 02/20/08 This program produces a 2D string art image by connectingvarious points that are equally spaced on the circumference of a circle.At startup, the program constructs and draws a multi- colored hexagon centered on the origin. The six pointsthat define the vertices of the hexagon lie on a circle with a radius of 100 units. The points at the vertices arenot drawn, but the lines that connect the vertices are drawn.A GUI is provided that allows the user to specify the following items and click a Replot button to cause thedrawing to change: Number PointsNumber Loops Changing the number of points causes the number ofvertices that describe the geometric object to change. Changing the number of loops causes the number of linesthat are drawn to connect the vertices to change. For a value of 1, each vertex is connected to the one next toit. For a value of 2, additional lines are drawn connecting every other vertex. For a value of 3,additional lines are drawn connecting every third vertex, etc.Making the number of points large and making the number of loops large produces many interesting patterns.Tested using JDK 1.6 under WinXP. *********************************************************/import java.awt.*; import javax.swing.*;import java.awt.geom.*; import java.awt.event.*;class StringArt01{ public static void main(String[]args){ GUI guiObj = new GUI();}//end main }//end controlling class StringArt01//======================================================// class GUI extends JFrame implements ActionListener{//Specify the horizontal and vertical size of a JFrame // object.int hSize = 300; int vSize = 320;Image osi;//an off-screen image int osiWidth;//off-screen image widthint osiHeight;//off-screen image height MyCanvas myCanvas;//a subclass of CanvasGraphics2D g2D;//Off-screen graphics context.int numberPoints = 6;//Can be modified by the user. JTextField numberPointsField; //User input field.JTextField loopsField;//User input field. int loopLim = 2;//The following variable is used to refer to the array// object containing the points that define the // vertices of the geometric object.GM2D04.Point[] points;//----------------------------------------------------//GUI(){//constructor //Instantiate the array object that will be used to// store the points that define the vertices of the // geometric object.points = new GM2D04.Point[numberPoints];//Set JFrame size, title, and close operation.setSize(hSize,vSize); setTitle("Copyright 2008,R.G.Baldwin");setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Instantiate the user input components. numberPointsField =new JTextField("6");loopsField = new JTextField("1"); JButton button = new JButton("Replot");//Instantiate a JPanel that will house the user input // components and set its layout manager.JPanel controlPanel = new JPanel(); controlPanel.setLayout(new GridLayout(3,3)); //Add the user input components and appropriate labels// to the control panel. controlPanel.add(new JLabel(" Number Points"));controlPanel.add(numberPointsField); controlPanel.add(new JLabel(" Number Loops"));controlPanel.add(loopsField); controlPanel.add(button);//Add the control panel to the SOUTH position in the // JFrame.this.getContentPane().add( BorderLayout.SOUTH,controlPanel);//Create a new drawing canvas and add it to the// CENTER of the JFrame above the control panel. myCanvas = new MyCanvas();this.getContentPane().add( BorderLayout.CENTER,myCanvas);//This object must be visible before you can get an // off-screen image. It must also be visible before// you can compute the size of the canvas. setVisible(true);//Make the size of the off-screen image match the// size of the canvas. osiWidth = myCanvas.getWidth();osiHeight = myCanvas.getHeight();//Create an off-screen image and get a graphics // context on it.osi = createImage(osiWidth,osiHeight); g2D = (Graphics2D)(osi.getGraphics());//Erase the off-screen image and draw the axessetCoordinateFrame(g2D,true); //Create the Point objects that define the geometric// object and manipulate them to produce the desired // results.drawOffScreen(g2D);//Register this object as an action listener on the // button.button.addActionListener(this); //Cause the overridden paint method belonging to// myCanvas to be executed. myCanvas.repaint();}//end constructor//----------------------------------------------------////The purpose of this method is to Create the Point // objects that define the vertices of the geometric// object and manipulate them to produce the desired // results.void drawOffScreen(Graphics2D g2D){ //Erase the off-screen image and draw new axes, but// don't move the origin. setCoordinateFrame(g2D,false);//Create a set of Point objects that specify// locations on the circumference of a circle and // save references to the Point objects in an array.for(int cnt = 0;cnt<numberPoints;cnt++){ points[cnt]= new GM2D04.Point( new GM2D04.ColMatrix(100*Math.cos((cnt*360/numberPoints) *Math.PI/180),100*Math.sin((cnt*360/numberPoints) *Math.PI/180)));}//end for loop//Implement the algorithm that draws the lines. GM2D04.Line line;//Begin the outer loop.for(int loop = 1;loop<loopLim;loop++){ //The following variable specifies the array// element containing a point on which a line will // start.int start = -1;//The following variable specifies the number of // points that will be skipped between the starting// point and the ending point for a line. int skip = loop;//The following logic causes the element number to // wrap around when it reaches the end of the// array. while(skip>= 2*numberPoints-1){ skip -= numberPoints;}//end while loop//The following variable specifies the array // element containing a point on which a line will// end. int end = start + skip;//Begin inner loop. This loop actually constructs // the GM2D04.Line objects and causes visual// manifestations of those objects to be drawn on // the off-screen image. Note the requirement to// wrap around when the element numbers exceed the // length of the array.for(int cnt = 0;cnt<numberPoints;cnt++){ if(start<numberPoints-1){ start++;}else{ //Wrap aroundstart -= (numberPoints-1); }//end elseif(end<numberPoints-1){ end++;}else{ //Wrap around.end -= (numberPoints-1); }//end else//Create some interesting colors.g2D.setColor(new Color(cnt*255/numberPoints, 127+cnt*64/numberPoints,255-cnt*255/numberPoints));//Create a line and draw it. line = new GM2D04.Line(points[start],points[end]);line.draw(g2D); }//end inner loop}//end outer loop }//end drawOffScreen//----------------------------------------------------// //This method is used to set the coordinate frame of// the off-screen image by setting the origin to the // center of the off-screen image and drawing black// orthogonal axes that intersect at the origin. //The second parameter is used to determine if the// origin should be translated to the center. private void setCoordinateFrame(Graphics2D g2D,boolean translate){ //Translate the origin to the center of the off-screen// image if the fourth parameter is true. if(translate){g2D.translate((int)osiWidth/2,(int)osiHeight/2); }//end if//Paint the background white g2D.setColor(Color.WHITE);g2D.fillRect(-(int)osiWidth/2,-(int)osiHeight/2, (int)osiWidth,(int)osiHeight);//Draw new X and Y-axes in BLACK g2D.setColor(Color.BLACK);g2D.drawLine(-(int)(osiWidth/2),0, (int)(osiWidth/2),0);g2D.drawLine(0,-(int)(osiHeight/2),0,(int)(osiHeight/2)); }//end setCoordinateFrame method//----------------------------------------------------////This method is called to respond to a click on the // button.public void actionPerformed(ActionEvent e){ //Get user input values and use them to modify several// values that control the drawing. numberPoints = Integer.parseInt(numberPointsField.getText()); loopLim = Integer.parseInt(loopsField.getText()) + 1;//Instantiate a new array object with a length // that matches the new value for numberPoints.points = new GM2D04.Point[numberPoints];//Draw a new off-screen image based on user inputs. drawOffScreen(g2D);myCanvas.repaint();//Copy off-screen image to canvas. }//end actionPerformed//====================================================////This is an inner class of the GUI class.class MyCanvas extends Canvas{ //Override the paint() method. This method will be// called when the JFrame and the Canvas appear on the // screen or when the repaint method is called on the// Canvas object. //The purpose of this method is to display the// off-screen image on the screen. public void paint(Graphics g){g.drawImage(osi,0,0,this); }//end overridden paint()}//end inner class MyCanvas}//end class GUI//======================================================//

Exercises

Exercise 1

Using Java and the game-math library named GM2D04 , , or using a different programming environment of your choice, write a programthat begins with an image showing:

  • Cartesian coordinate axes with the origin at the center of the image,
  • a small black pentagon centered on the origin, and
  • a button labeled Replot

No user input controls other than the button should be visible in your image.

Make each side of the pentagon approximately one-half inch in length as shown in Figure 10 .

Each time you click the Replot button, a red pentagon appears on top of the black pentagon and then movessmoothly to a random location somewhere in the image as shown in Figure 11 .

If you click the button more than once, the old red pentagon is erased and a new red pentagon appears andmoves as described above.

Move the red pentagon in a straight line in approximately 100 incremental steps over a time period of approximatelyone second.

Cause the program to display your name in some manner.

Figure 10 Screen output from Exercise 1 at startup.

Missing image.

Figure 11 Screen output from Exercise 1 after clicking Replot button.

Missing image.

-end-

Questions & Answers

Discuss the differences between taste and flavor, including how other sensory inputs contribute to our  perception of flavor.
John Reply
taste refers to your understanding of the flavor . while flavor one The other hand is refers to sort of just a blend things.
Faith
While taste primarily relies on our taste buds, flavor involves a complex interplay between taste and aroma
Kamara
which drugs can we use for ulcers
Ummi Reply
omeprazole
Kamara
what
Renee
what is this
Renee
is a drug
Kamara
of anti-ulcer
Kamara
Omeprazole Cimetidine / Tagament For the complicated once ulcer - kit
Patrick
what is the function of lymphatic system
Nency Reply
Not really sure
Eli
to drain extracellular fluid all over the body.
asegid
The lymphatic system plays several crucial roles in the human body, functioning as a key component of the immune system and contributing to the maintenance of fluid balance. Its main functions include: 1. Immune Response: The lymphatic system produces and transports lymphocytes, which are a type of
asegid
to transport fluids fats proteins and lymphocytes to the blood stream as lymph
Adama
what is anatomy
Oyindarmola Reply
Anatomy is the identification and description of the structures of living things
Kamara
what's the difference between anatomy and physiology
Oyerinde Reply
Anatomy is the study of the structure of the body, while physiology is the study of the function of the body. Anatomy looks at the body's organs and systems, while physiology looks at how those organs and systems work together to keep the body functioning.
AI-Robot
what is enzymes all about?
Mohammed Reply
Enzymes are proteins that help speed up chemical reactions in our bodies. Enzymes are essential for digestion, liver function and much more. Too much or too little of a certain enzyme can cause health problems
Kamara
yes
Prince
how does the stomach protect itself from the damaging effects of HCl
Wulku Reply
little girl okay how does the stomach protect itself from the damaging effect of HCL
Wulku
it is because of the enzyme that the stomach produce that help the stomach from the damaging effect of HCL
Kamara
function of digestive system
Ali Reply
function of digestive
Ali
the diagram of the lungs
Adaeze Reply
what is the normal body temperature
Diya Reply
37 degrees selcius
Xolo
37°c
Stephanie
please why 37 degree selcius normal temperature
Mark
36.5
Simon
37°c
Iyogho
the normal temperature is 37°c or 98.6 °Fahrenheit is important for maintaining the homeostasis in the body the body regular this temperature through the process called thermoregulation which involves brain skin muscle and other organ working together to maintain stable internal temperature
Stephanie
37A c
Wulku
what is anaemia
Diya Reply
anaemia is the decrease in RBC count hemoglobin count and PVC count
Eniola
what is the pH of the vagina
Diya Reply
how does Lysin attack pathogens
Diya
acid
Mary
I information on anatomy position and digestive system and there enzyme
Elisha Reply
anatomy of the female external genitalia
Muhammad Reply
Organ Systems Of The Human Body (Continued) Organ Systems Of The Human Body (Continued)
Theophilus Reply
what's lochia albra
Kizito
Got questions? Join the online conversation and get instant answers!
Jobilize.com Reply

Get Jobilize Job Search Mobile App in your pocket Now!

Get it on Google Play Download on the App Store Now




Source:  OpenStax, Game 2302 - mathematical applications for game development. OpenStax CNX. Jan 09, 2016 Download for free at https://legacy.cnx.org/content/col11450/1.33
Google Play and the Google Play logo are trademarks of Google Inc.

Notification Switch

Would you like to follow the 'Game 2302 - mathematical applications for game development' conversation and receive update notifications?

Ask