How can i move a triangle x and y coordinates in Java Polygo

How can i move a triangle (x and y coordinates) in Java?

Polygon triangle = new Polygon( );

g.setColor(Color.BLUE);

triangle.addPoint( 75, 50 );

triangle.addPoint( 25, 150 );

triangle.addPoint( 125, 150 );

g.drawPolygon ( triangle );

g.fillPolygon(triangle);

Solution

You can simply create variables for each of the 3 coordinates like x1, y1, x2, y2, x3, y3 [as is demonstrated in the below code]. At any point while executing the code you can change the values of these coordinates to move the triangle.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Polygon;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Triangle extends JPanel {

   private int x1, y1;
   private int x2, y2;
   private int x3, y3;
  
   /**
   * Constructor
   */
   public Triangle() {
       super();
       x1 = 75;
       y1 = 50;
       x2 = 25;
       y2 = 150;
       x3 = 125;
       y3 = 150;
   }

   public void paint(Graphics g) {
       Polygon triangle = new Polygon( );
       g.setColor(Color.BLUE);
       triangle.addPoint(x1, y1);
       triangle.addPoint(x2, y2);
       triangle.addPoint(x3, y3);
       g.drawPolygon ( triangle );
       g.fillPolygon(triangle);
   }
  
   public static void main(String[] args) {
       // Create main frame
       JFrame frame = new JFrame();
       frame.setSize(new Dimension(450, 450));
       frame.setResizable(false);

       // Add the main panel to the frame
       frame.add(new Triangle());

       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       frame.setLocationRelativeTo(null);
       frame.setVisible(true);
   }
}

How can i move a triangle (x and y coordinates) in Java? Polygon triangle = new Polygon( ); g.setColor(Color.BLUE); triangle.addPoint( 75, 50 ); triangle.addPoi
How can i move a triangle (x and y coordinates) in Java? Polygon triangle = new Polygon( ); g.setColor(Color.BLUE); triangle.addPoint( 75, 50 ); triangle.addPoi

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site