Share & learn

Through Innovative Digital Library

How to draw a triangle in Java?

Write a piece of code in Java to draw a triangle.
 



Answers

Posted by Paul on April 24th 2018 06:17 AM

Program to draw a triangle in Java : For drawing a circle in Java you can use Line2D class provided by java in java.awt.geom.* package. This class provides a line segment in (x, y) coordinate space. You just need to draw three lines using Line2D Class in order to draw a triangle. setPaint() : This method paints the line segment Here is the code :

// Java program to draw triangle
import java.awt.*;
import javax.swing.*;
import java.awt.geom.Line2D;

public class 
DrawTriangle extends JApplet {
    public 
void init() {
        
setBackground(Color.lightGray);
    }

    
// method to draw triangle
    
public void paint(Graphics g) {
        
Graphics2D graphics = (Graphics2Dg;
        
graphics.setPaint(Color.black);
        
        
// draw three line segments in order to create triangle
        
graphics.draw(new Line2D.Double(50150150150));
        
graphics.draw(new Line2D.Double(5050150150));
        
graphics.draw(new Line2D.Double(505050150));
    }

    public static 
void main(String s[]) {
        
        
// create frame
        
JFrame frame = new JFrame("Draw Triangle");
        
        
JApplet applet = new DrawTriangle();
        
frame.getContentPane().add("Center"applet);
        
applet.init();
        
        
// set size of frame
        
frame.setSize(300250);
        
frame.show();
    }
}
Answer Question

Your email address will not be published. Required fields are marked *

  • Minimum 20 character
RAGG

related questions

Most liked questions

Most answered questions

Login
RAGG Refresh
Register
RAGG Refresh
Forgot password
Ask a Question
Minimum 20 character
Minimum 20 character
Reply
Minimum 20 character
RAGG Refresh