This page is optimized for mobile devices, if you would prefer the desktop version just
click here
Listing 19 . Source code for the program named VectorAdd05a.
/*VectorAdd05a.java
Copyright 2008, R.G.BaldwinRevised 02/19/08
This program is a modified version of VectorAdd05 thatuses a different scheme for modifying the vertices of the
geometric object.Note that the comments in this program were not updated
to reflect these modifications. In particular, thisversion does not call the method named addVectorToPoint.
--------------------------------------------------------The purpose of this program is to use the addVectorToPoint
method of the GM2D04.Point class to translate a geometric
object from one location in space to a different locationin space. Along the way, the program uses various methods
of the classes in the game math library named GM2D04 toaccomplish its purpose.
The program initially constructs and draws a black hexagoncentered on the origin. The six points that define the
vertices of the hexagon lie on a circle with a radius of50 units. The points at the vertices and the lines that
connect the points are drawn.In addition, the program initially causes the hexagon to
be translated by 50 units in the positive X direction and50 units in the positive Y. The translated hexagon is
drawn in red. The original black hexagon is not erasedwhen the translated version is drawn in red.
A GUI is provided that allows the user to specify thefollowing items and click a Replot button to cause the
drawing to change:Number points
X-component of the displacement vector.Y-component of the displacement vector.
A checkbox to specify whether points are to be drawn.A checkbox to specify whether lines are to be drawn.
Changing the number of points causes the number ofvertices that describe the geometric object to change.
For a large number of points, the geometric object becomesa circle. For only three points, it becomes a triangle.
For four points, it becomes a square. For two points, itbecomes a line, etc.
Changing the components of the displacement vector causesthe geometric object to be translated to a different
location before being drawn in red.Checking and unchecking the checkboxes causes the points
and/or the lines to either be drawn or not drawn.Tested using JDK 1.6 under WinXP.
*********************************************************/import java.awt.*;
import javax.swing.*;import java.awt.geom.*;
import java.awt.event.*;class VectorAdd05a{
public static void main(String[]args){
GUI guiObj = new GUI();}//end main
}//end controlling class VectorAdd05a//======================================================//
class GUI extends JFrame implements ActionListener{//Specify the horizontal and vertical size of a JFrame
// object.int hSize = 400;
int vSize = 400;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.//The following two variables are used to establish the
// location of the origin.double xAxisOffset;
double yAxisOffset;int numberPoints = 6;//Can be modified by the user.JTextField numberPointsField; //User input field.
//The components of the following displacement vector// can be modified by the user.
GM2D04.Vector vector =new GM2D04.Vector(new GM2D04.ColMatrix(50,50));
JTextField vectorX;//User input field.JTextField vectorY;//User input field.//The following variables are used to determine whether
// to draw the points and/or the lines.boolean drawPoints = true;
boolean drawLines = true;Checkbox drawPointsBox;//User input field
Checkbox drawLinesBox;//User input field.//The following variables are used to refer to array// objects containing the points that define the
// vertices of the geometric object.GM2D04.Point[] points;// GM2D04.Point[] newPoints; //----------------------------------------------------//GUI(){//constructor//Instantiate the array objects that will be used to
// store the points that define the vertices of the// geometric object.
points = new GM2D04.Point[numberPoints];
// newPoints = 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");
vectorX = new JTextField("50");vectorY = new JTextField("50");
drawPointsBox = new Checkbox("Draw Points",true);drawLinesBox = new Checkbox("Draw Lines",true);
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 component and appropriate labels
// to the control panel.controlPanel.add(new JLabel(" Number Points"));
controlPanel.add(numberPointsField);controlPanel.add(drawPointsBox);
controlPanel.add(new JLabel(" Vector X"));controlPanel.add(vectorX);
controlPanel.add(drawLinesBox);controlPanel.add(new JLabel(" Vector Y"));
controlPanel.add(vectorY);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();//Set the values that will be used to establish the// origin, thus defining a coordinate frame.
xAxisOffset = osiWidth/2;yAxisOffset = osiHeight/2;//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,xAxisOffset,yAxisOffset,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 change the coordinate frame.
setCoordinateFrame(g2D,xAxisOffset,yAxisOffset,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(50*Math.cos((cnt*360/numberPoints)
*Math.PI/180),50*Math.sin((cnt*360/numberPoints)
*Math.PI/180)));if(drawPoints){//Draw points if true
points[cnt].draw(g2D);
}//end if}//end for loopGM2D04.Line line;
if(drawLines){//Instantiate and draw lines if true.for(int cnt = 0;cnt<numberPoints-1;cnt++){
//Begin by drawing all of the lines but one.line = new GM2D04.Line(points[cnt],points[cnt+1]);
line.draw(g2D);}//end for loop
//Draw the remaining line required to close the// polygon.
line = new GM2D04.Line(points[numberPoints-1],
points[0]);
line.draw(g2D);}//end ifg2D.setColor(Color.RED);//Change drawing color to RED.//Translate the geometric object and save the points
// that define the translated object in the same// array object.
for(intcnt = 0;cnt<numberPoints;cnt++){
points[cnt].setData(
0,points[cnt].getData(0) + vector.getData(0));
points[cnt].setData(
1,points[cnt].getData(1) + vector.getData(1));
if(drawPoints){//Draw points if true.points[cnt].draw(g2D);}//end if
}//end for loopif(drawLines){//Instantiate and draw lines if true.for(int cnt = 0;cnt<numberPoints-1;cnt++){
line = new GM2D04.Line(points[cnt],
points[cnt+1]);
line.draw(g2D);}//end for loop
//Draw the remaining line required to close the// polygon.
line = new GM2D04.Line(points[numberPoints-1],
points[0]);
line.draw(g2D);}//end if
}//end drawOffScreen//----------------------------------------------------//
//This method is used to set the coordinate frame of// the off-screen image by setting the origin to the
// specified offset values relative to origin of the// world. The origin of the world is the upper-left
// corner of the off-screen image.//The method draws black orthogonal axes on the
// off-screen image.//There is no intention to perform mathematical
// operations on the axes, so they are drawn// independently of the classes and methods in the
// game-math library using the simplest available method// for drawing lines.
//The method assumes that the origin is at the// upper-left corner when the method is first called.
//Each time the method is called, it paints the// background white erasing anything already there.
//The fourth parameter is used to determine if the// origin should be translated by the values of the
// second and third parameters.private void setCoordinateFrame(Graphics2D g2D,
double xOffset,double yOffset,
boolean translate){//Paint the background white
g2D.setColor(Color.WHITE);g2D.fillRect(-(int)xOffset,-(int)yOffset,
(int)osiWidth,(int)osiHeight);//Translate the origin by the specified amount if the
// fourth parameter is true.if(translate){
g2D.translate((int)xOffset,(int)yOffset);}//end if
//Draw new X and Y-axes in BLACKg2D.setColor(Color.BLACK);
g2D.drawLine(-(int)(xOffset - 10),0,(int)(xOffset - 10),0);g2D.drawLine(0,-(int)(yOffset - 10),
0,(int)(yOffset - 10));}//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 translation and the// drawing.
numberPoints = Integer.parseInt(numberPointsField.getText());
vector.setData(0,Double.parseDouble(vectorX.getText()));
vector.setData(1,Double.parseDouble(vectorY.getText()));
if(drawPointsBox.getState()){drawPoints = true;
}else{drawPoints = false;
}//end elseif(drawLinesBox.getState()){drawLines = true;
}else{drawLines = false;
}//end else//Instantiate two new array objects with a length// that matches the new value for numberPoints.
points = new GM2D04.Point[numberPoints];
// newPoints = 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
//======================================================//
Read also:
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.