draw Triangle

help....i need cant find any code to draw a triangle in java. i need to let user click and drag on the canvas to draw the triangle. Any help will be appreciated.

[168 byte] By [don.juan9a] at [2007-11-27 11:26:24]
# 1

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.event.MouseInputAdapter;

public class TriangleDrag extends JPanel {

Polygon triangle;

protected void paintComponent(Graphics g) {

super.paintComponent(g);

Graphics2D g2 = (Graphics2D)g;

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

if(triangle != null)

g2.draw(triangle);

}

public void setTriangle(Point p1, Point p2) {

int R = (int)p1.distance(p2);

int cx = p1.x;

int cy = p1.y + R;

int[][] coords = generateShapeArrays(cx, cy, R, 3);

triangle = new Polygon(coords[0], coords[1], 3);

repaint();

}

private int[][] generateShapeArrays(int cx, int cy, int R, int sides) {

int radInc = 0;

if(sides % 2 == 0)

radInc = 1;

int[] x = new int[sides];

int[] y = new int[sides];

for(int j = 0; j < sides; j++) {

x[j] = cx + (int)(R * Math.sin(radInc*Math.PI/sides));

y[j] = cy - (int)(R * Math.cos(radInc*Math.PI/sides));

radInc += 2;

}

// Keep base of triangle level.

if(sides == 3)

y[2] = y[1];

return new int[][] { x, y };

}

public static void main(String[] args) {

TriangleDrag test = new TriangleDrag();

TriangleCreator creator = new TriangleCreator(test);

test.addMouseListener(creator);

test.addMouseMotionListener(creator);

JFrame f = new JFrame();

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.getContentPane().add(test);

f.setSize(400,400);

f.setLocation(200,200);

f.setVisible(true);

}

}

class TriangleCreator extends MouseInputAdapter {

TriangleDrag component;

Point start;

public TriangleCreator(TriangleDrag td) { component = td; }

public void mousePressed(MouseEvent e) { start = e.getPoint(); }

public void mouseDragged(MouseEvent e) {

component.setTriangle(start, e.getPoint());

}

}

crwooda at 2007-7-29 16:10:13 > top of Java-index,Security,Cryptography...