Programer171
Programer171

Reputation: 3

How can we merge shapes in Java awt?

I am trying to merge two shapes into one object which can be used to draw the merged shape on the window with Graphics2D.for example 2 rounded rectangles with one of the rounded rectangles rotated 90 degrees merged into one shape. I searched SO for possible solutions but all of them were talking about algorithms which create shapes out of 2 or more shapes using vertexes(I can't really use them with the Graphics 2D library), I also tried to googling it, which just gave solutions in JavaFX which is not what I am using. I had also tried out some code myself, but it was still using two shape objects. Here's what I've tried :


import javax.swing.*;
import java.awt.*;

public class Red extends JPanel {
    public Red(Color c, int width, int height){
        this.setBackground(c);
        this.setSize(width, height);
    }

    @Override
    public void paint(Graphics g) {
        Graphics2D gtd = (Graphics2D) g;
        gtd.setColor(Color.red);
        gtd.fillRoundRect(500,500,50,15, 3, 3);
        gtd.rotate(Math.toRadians(90),525,500 + 15/2 );
        gtd.fillRoundRect(500,500,50,15, 3, 3);
    }
}

I want to merge:


        gtd.fillRoundRect(500,500,50,15, 3, 3);
        gtd.rotate(Math.toRadians(90),525,500 + 15/2 );
        gtd.fillRoundRect(500,500,50,15, 3, 3);

into one shape that can be used as a normal rectangle object and be drawn such as:

MergedShape X = new MergedShape(x,y, width, height)
gtd.draw(X);

finally, So to put it short : How can we merge 2 shapes into one, that can also be used as a normal shape with the Graphics2D method?

thanks in advance!

Upvotes: 0

Views: 772

Answers (1)

mipa
mipa

Reputation: 10650

What you are looking for is the AWT java.awt.geom.Area class. https://docs.oracle.com/en/java/javase/16/docs/api/java.desktop/java/awt/geom/Area.html

Upvotes: 1

Related Questions