hi
how would i construct the draw method for an triangle using the 'public void draw (graphics g ) method? im unsure how to use the g.fillPolygon and g.drawPolygon?
i have this for drawing a rectangle and this works for a rectangle:
public void draw(Graphics g) { g.setColor(colorFill); g.fillRect(p.x, p.y, width, height); g.setColor(colorBorder); g.drawRect(p.x, p.y, width, height); drawHandles(g); }
Here is an example that draws a triangle using drawPolygon method.
import java.awt.*; import javax.swing.*; import java.awt.event.*; public class DrawTriangle extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.red); Polygon polygon1= new Polygon(); for (int i = 0; i < 3; i++){ polygon1.addPoint((int) (40 + 50 * Math.cos(i * 2 * Math.PI / 3)), (int) (150 + 50 * Math.sin(i * 2 * Math.PI / 3))); } g.drawPolygon(polygon1); } public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(350, 250); Container contentPane = frame.getContentPane(); contentPane.add(new DrawTriangle()); frame.show(); } }
If you want to use Line2D class to draw a triangle, then please go through the following link:
http://www.roseindia.net/java/example/java/swing/graphics2D/triangle-line2d.shtml
Ads