Create 2D shape in Java

To create a 2D shape in Java Swing, we can use the Graphics2D class, which provides a set of methods to draw and manipulate shapes.

Following is an example of how to create a simple rectangle shape:

import java.awt.Graphics;
import java.awt.Graphics2D;

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

public class Swing2DShapeDemo extends JPanel {
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawRect(50, 50, 100, 100);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("2D Shape Demo");
        frame.add(new Swing2DShapeDemo());
        frame.setSize(300, 300);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

}

In this example, we create a new class called Swing2DShapeDemo that extends JPanel and overrides its paintComponent method. Inside the paintComponent method, we cast the Graphics object to a Graphics2D object, so that we can use its 2D drawing capabilities. We then use the drawRect method to draw a rectangle shape with a position of (50, 50) and a size of 100×100.

To run the code, we create a JFrame object, add an instance of Swing2DShapeDemo to it, set the size and visibility of the frame, and specify that the program should exit when the user closes the frame.

The output of the above code looks like:

Create 2D shape in Java DrawReact 2d demo

We can modify the parameters of drawRect to create different shapes, or use other methods like drawOval, drawLine, and drawPolygon to create different kinds of shapes.

To draw a line we can use the method drawLine() from Graphics2D class.

Example code:

g2d.drawLine(50, 50, 100, 100);

Output:

Create 2D shape in Java 2d draw line

If you’ve noticed in the above code, I’ve changed only the method name from drawReact to drawLine. The parameter values haven’t been changed and it draws the line.

You can learn more from the official documentation: https://docs.oracle.com/javase/tutorial/2d/basic2d/index.html

Sharing Is Caring: