Search code examples
javagraphics2d

Fill Color Custom Shape Java


I want to fill a color inside of my custom shape

here is my code for trapezium shape

Trapezium Class

public class Trapezium implements Shape {
private GeneralPath trapezium = new GeneralPath();

public Trapezium (Point2D A, double height, double width)
{

    double Ax = A.getX();
    double Ay = A.getY();

    double Bx = Ax + (width/6);
    double By = Ay;

    double Cx = Bx + (width/3);
    double Cy = By + height;

    double Dx = Cx - width;
    double Dy = Cy;

    double Ex = Dx + (width/3);
    double Ey = Dy - height;


    trapezium.moveTo(Ax, Ay);
    trapezium.lineTo(Bx, By);
    trapezium.lineTo(Cx, Cy);
    trapezium.lineTo(Dx, Dy);
    trapezium.lineTo(Ex, Ey);
    trapezium.closePath();

}

@Override
public java.awt.Rectangle getBounds() {
    return trapezium.getBounds();
}

@Override
public Rectangle2D getBounds2D() {
    return trapezium.getBounds2D();
}

@Override
public boolean contains(double x, double y) {
    return trapezium.contains(x, y);
}

@Override
public boolean contains(Point2D p) {
    return trapezium.contains(p);
}

@Override
public boolean intersects(double x, double y, double w, double h) {
    return trapezium.intersects(x, y, w, h);
}

@Override
public boolean intersects(Rectangle2D r) {
        return trapezium.intersects(r);
}

@Override
public boolean contains(double x, double y, double w, double h) {
    return trapezium.contains(x, y,w ,h);
}

@Override
public boolean contains(Rectangle2D r) {
    return trapezium.contains(r);
}

@Override
public PathIterator getPathIterator(AffineTransform at) {
    return trapezium.getPathIterator(at);
}

@Override
public PathIterator getPathIterator(AffineTransform at, double flatness) {
    return trapezium.getPathIterator(at, flatness);
}
}

Here's my code when i call the trapezium class

DrawPanel Class

else if(type.get(a).equals("Trapezium"))
{
    int[]coordinates=allShapes.get(a);
    Point2D b= new Point2D.Double(coordinates[0], coordinates[1]);

    Trapezium trapezium = new Trapezium(b,coordinates[3], coordinates[2]);
    g2.setStroke(new BasicStroke(coordinates[4]));
    g2.setPaint(dragColor);
    g2.draw(trapezium);
}

the setPaint only colors the stroke of my shape , how do i color the inside of the shape ?

Image of my current code when executed

EDIT

I have 2 JColorChooser, 1 is for the stroke of the shape , and 2 is for the color inside the shape

if i use the

g2.setPaint(color2) g2.fill(trapezium)

how do i get the color1 to change the color of my stroke ?


Solution

  • you have to simply fill the shape ^_^

    Trapezium trapezium = new Trapezium(b,coordinates[3], coordinates[2]);
    g2.setStroke(new BasicStroke(coordinates[4]));
    g2.setPaint(dragColor);
    g2.fill(trapezium); //HERE!!!!