To draw a triangle in Java, you can use the Graphics
class and its drawLine()
method to draw three lines that form a triangle.
Here's an example of how to draw a triangle in Java using the Graphics
class:
import java.awt.Graphics; public class Triangle { public void draw(Graphics g) { // Set the color of the lines g.setColor(Color.BLACK); // Draw three lines to form a triangle g.drawLine(10, 10, 50, 10); g.drawLine(50, 10, 30, 30); g.drawLine(30, 30, 10, 10); } }
In the above example, the draw()
method accepts a Graphics
object as an argument and uses it to draw three lines that form a triangle. The drawLine()
method takes four arguments: the x and y coordinates of the start point and the end point of the line.
You can adjust the position and size of the triangle by changing the coordinates of the lines.
To display the triangle on a graphical user interface (GUI), you can create a custom component that extends JPanel
and overrides the paintComponent()
method. Then, you can add the custom component to a JFrame
or any other container.
Here's an example of how to display a triangle on a GUI in Java:
import javax.swing.JFrame; import javax.swing.JPanel; public class TriangleFrame extends JFrame { public TriangleFrame() { } }