Search code examples
javaswinggraphics2d

Filling a rectangle in Java


I did some heavy googling on how to fill a rectangle using graphics2D.

I currently want to make the German flag, so three rectangles. But right now I want to just fill one rectangle and see how that goes.

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Line2D;
import javax.swing.JComponent;

public class germanflag
{
    public void paintComponent(Graphics g)
    {
        Graphics2D g2 = (Graphics2D) g;

        // Construct flag
        Rectangle flag = new Rectangle(0, 0, 120, 60); 

        Graphics2D g2d = flag;
        g2d.setColor(Color.RED);
        g2d.fillRect(0,0,120,60);
        // draw the rectangle
        g2.draw(flag); 

    }
}

Obviously an error is coming up. I just don't know how to rectify it. Should the rectangle be created as I do the filling, or should it be initialized beforehand, as in this code?


Solution

  • Problem is you are trying to cast/assign instance/object of type Rectangle to Grapichs2D.

    //Graphics2D g2d = flag; //not required
    g2d.setColor(Color.RED); //use g2 instead
    g2d.fillRect(0,0,120,60);//use g2 instead
    

    P.S. the class germanflag doesn't extends any Swing component. You might be possibly looking for JComponent or JPanel.