<< Chapter < Page Chapter >> Page >

Listing 31 . Source code for the program named StringArt02.

/*StringArt02.java Copyright 2008, R.G.BaldwinRevised 02/22/08 This is a 2D version of a string art program that supportsrotation in two dimensions. This program produces a 2D string art image by connectingvarious points that are equally spaced on the circumference of a circle.Initially, the circle is centered on the origin. There are six points on the circle connected by lines forming ahexagon, The lines that connect the points are different colors. The radius of the circle is 50 units. The pointsat the vertices of the hexagon are not 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 Rotation angle (deg)X anchor point Y anchor pointChanging the number of points causes the number of vertices that describe the geometric object to change.Changing the number of loops causes the number of lines that are drawn to connect the vertices to change. For avalue of 1, each vertex is connected to the one next to it. For a value of 2, additional lines are drawnconnecting every other vertex. For a value of 3, additional lines are drawn connecting every third vertex,etc. The image can be rotated around an anchor point. Enteringa non-zero value in the Rotation field causes the image to be rotated by the specified angle around the anchorpoint. The anchor point is initially located at the origin, butthe location of the anchor point can be changed by the user. If the anchor point is at the origin, the image isrotated around the origin. Otherwise, the image is rotated around the point in 2D space specified by the anchorpoint. The anchor point is drawn in black. The rotation angle is specified in degrees with a positiveangle being counter-clockwise. The number of points is initially set to six and thenumber of loops is initially set to one. Making the number of points larger and making the number of loopslarger 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 StringArt02{public static void main(String[] args){GUI guiObj = new GUI(); }//end main}//end controlling class StringArt02 //======================================================//class GUI extends JFrame implements ActionListener{ //Specify the horizontal and vertical size of a JFrame// object. int hSize = 300;int vSize = 470; Image osi;//an off-screen imageint osiWidth;//off-screen image width int osiHeight;//off-screen image heightMyCanvas myCanvas;//a subclass of Canvas Graphics2D g2D;//off-screen graphics context.JTextField numberPointsField;//User input field. JTextField loopsField;//User input field.int numberPoints = 6;//Can be modified by the user. int loopLim = 1;//Can be modified by the user.JTextField rotationField;//User input fielddouble rotation;//Rotation angle in degrees clockwise.JTextField xAnchorPointField;//User input field JTextField yAnchorPointField;//User input fielddouble xAnchorPoint;//Rotation anchor point. double yAnchorPoint;//Rotation anchor point.//The following variable is used to refer to an array// object containing the points that define the // vertices of a geometric object.GM01.Point2D[] 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 GM01.Point2D[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");rotationField = new JTextField("0"); xAnchorPointField = new JTextField("0");yAnchorPointField = new JTextField("0"); 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(0,2));//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(new JLabel( " Rotation angle (deg)"));controlPanel.add(rotationField); controlPanel.add(new JLabel(" X anchor point"));controlPanel.add(xAnchorPointField); controlPanel.add(new JLabel(" Y anchor point"));controlPanel.add(yAnchorPointField); 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, establish the origin,// and draw the axes setCoordinateFrame(g2D,true);//Create the Point2D 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 Point2D // objects that define the vertices of a 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 Point2D objects that specify // locations on the circumference of a circle that// is in the x-y plane with a radius of 50 units. Save // references to the Point2D objects in an array.for(int cnt = 0;cnt<numberPoints;cnt++){ points[cnt]= new GM01.Point2D(new GM01.ColMatrix2D( 50*Math.cos((cnt*360/numberPoints)*Math.PI/180),50*Math.sin((cnt*360/numberPoints)*Math.PI/180)));//The following object is populated with the 2D // coordinates of the point around which the//rotations will take place. GM01.Point2D anchorPoint = new GM01.Point2D(new GM01.ColMatrix2D( xAnchorPoint,yAnchorPoint));//Draw the anchorPoint in BLACK. g2D.setColor(Color.BLACK);anchorPoint.draw(g2D);//The following statement causes the rotation to be //performed.points[cnt] =points[cnt].rotate(anchorPoint,rotation);}//end for loop//Implement the algorithm that draws lines connecting // points on the geometric object.GM01.Line2D 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 GM01.Line2D 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 that connects points on the // geometric object.line = new GM01.Line2D(points[start],points[end]); line.draw(g2D);}//end inner loop }//end outer loop}//end drawOffScreen //----------------------------------------------------////This method is used to set the origin of the // off-screen image to the center and to draw orthogonal// 2D axes on the image 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 if translate is// true. if(translate){GM01.translate(g2D,0.5*osiWidth,-0.5*osiHeight); }//end if//Erase the screeng2D.setColor(Color.WHITE); GM01.fillRect(g2D,-osiWidth/2,osiHeight/2,osiWidth,osiHeight); //Draw x-axis in REDg2D.setColor(Color.RED); GM01.Point2D pointA = new GM01.Point2D(new GM01.ColMatrix2D(-osiWidth/2,0)); GM01.Point2D pointB = new GM01.Point2D(new GM01.ColMatrix2D(osiWidth/2,0)); new GM01.Line2D(pointA,pointB).draw(g2D);//Draw y-axis in GREENg2D.setColor(Color.GREEN); pointA = new GM01.Point2D(new GM01.ColMatrix2D(0,-osiHeight/2)); pointB = new GM01.Point2D(new GM01.ColMatrix2D(0,osiHeight/2)); new GM01.Line2D(pointA,pointB).draw(g2D);}//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());//Rotation angle in degrees. rotation =Double.parseDouble(rotationField.getText()); //Rotation anchor pointsxAnchorPoint = Double.parseDouble(xAnchorPointField.getText());yAnchorPoint = Double.parseDouble(yAnchorPointField.getText());//Instantiate a new array object with a length // that matches the new value for numberPoints.points = new GM01.Point2D[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//======================================================//

Questions & Answers

how did the oxygen help a human being
Achol Reply
how did the nutrition help the plants
Achol Reply
Biology is a branch of Natural science which deals/About living Organism.
Ahmedin Reply
what is phylogeny
Odigie Reply
evolutionary history and relationship of an organism or group of organisms
AI-Robot
ok
Deng
what is biology
Hajah Reply
cell is the smallest unit of the humanity biologically
Abraham
what is biology
Victoria Reply
what is biology
Abraham
HOW CAN MAN ORGAN FUNCTION
Alfred Reply
the diagram of the digestive system
Assiatu Reply
allimentary cannel
Ogenrwot
How does twins formed
William Reply
They formed in two ways first when one sperm and one egg are splited by mitosis or two sperm and two eggs join together
Oluwatobi
what is genetics
Josephine Reply
Genetics is the study of heredity
Misack
how does twins formed?
Misack
What is manual
Hassan Reply
discuss biological phenomenon and provide pieces of evidence to show that it was responsible for the formation of eukaryotic organelles
Joseph Reply
what is biology
Yousuf Reply
the study of living organisms and their interactions with one another and their environment.
Wine
discuss the biological phenomenon and provide pieces of evidence to show that it was responsible for the formation of eukaryotic organelles in an essay form
Joseph Reply
what is the blood cells
Shaker Reply
list any five characteristics of the blood cells
Shaker
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