user7883651
user7883651

Reputation: 11

Filling shape made of Line2D with color

In java I create closed shape by conecting Points using Lines 2D. How can I paint it/fill with color?

Upvotes: 0

Views: 1572

Answers (2)

VGR
VGR

Reputation: 44413

First, create a single Shape by appending your lines to a Path2D:

private Path2D createSingleShape(Line2D[] lines) {
    Path2D path = new Path2D.Float();

    for (Line2D line : lines) {
        path.append(line, path.getCurrentPoint() != null);
    }

    path.closePath();

    return path;
}

Then, pass it to Graphics2D.fill(Shape):

@Override
protected void paintComponent(Graphics graphics) {
    super.paintComponent(graphics);

    Graphics2D g = (Graphics2D) graphics;

    Shape shape = createSingleShape(lines);
    g.fill(shape);
}

Upvotes: 2

Luatic
Luatic

Reputation: 11201

I dont know what your code is, but I assume you have a class that looks like this :

You are searching for the fillPolygon(int[] xpoints, int[] ypoints, int nPoints) method

public class App extends JFrame{
    public App() {
        super("Paintings");
        requestFocus();
        DrawingPane dpane=new DrawingPane();
        setContentPane(dpane);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 600);
        setResizable(true);
        setVisible(true);
        long start = System.currentTimeMillis();
        while (true){
            long now = System.currentTimeMillis();
            if (now-start > 10) { //FPS
                start=now;
                dpane.revalidate();
                dpane.repaint();
            }
        }
    }
    public static void main(String[] args) {
        new App();
    }
    class DrawingPane extends JPanel{
        @Override
        public void paintComponent(Graphics g2){
            Graphics2D g=(Graphics2D)g2;
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g.setColor(Color.BLACK);
            //-THE DRAWING-
            //You wont need any lines
            Point[] points=new Point[] {new Point(0,0),new Point(1,0),new Point(1,1)};
            int[] points_x=new int[points.length];
            int[] points_y=new int[points.length];
            for (int p=0; p < points.length; p++) {
                 points_x[p]=points[p].x;
                 points_y[p]=points[p].y;
            }
            g.drawPolygon(points_x,points_y,points.length); //Draw the outlines
            g.fillPolygon(points_x,points_y,points.length); //Filled Polygon
        }
    }
}

Upvotes: 0

Related Questions