Search code examples
javaswinggraphics2d

Restricting the drawing area on a JPanel and saving graphics states


The purpose of the black JPanel is drawing.

  • How can I restrict the drawing to the radius of the circle formed by the lines?

  • Is there a way to save the graphics object state so that more drawing can be added to it as well as adding an undo function?

enter image description here

public void paintComponent(Graphics g)
{
    super.paintComponent(g);

    sectors = 12;

    Graphics2D g2d = (Graphics2D) g;    
    g2d.setColor(Color.RED);

    sector = new Line2D.Double(getWidth()/2, 0, getWidth()/2, getHeight());
    //g2d.setClip(new Ellipse2D.Double(getWidth()/2,getHeight()/2, radius, radius));


    //draws the sectors on the screen
    for(int i=0; i<sectors; i++)
    {   
        g2d.draw(sector);
        g2d.rotate(Math.toRadians(30),getWidth()/2,getHeight()/2);
    }

    //draws the doily
    if(dragging)
    {
        for(int i=0; i<sectors; i++)
        {
            g2d.fillOval((int) draw.getX(), (int) draw.getY(),20, 20);
            g2d.rotate(Math.toRadians(30), getWidth()/2, getHeight()/2);
        }

        //saves the current drawing in a stack
        graphics.push(g2d);
    }
}

Solution

  • For your first question,

    You would need to read up on Java's Custom Painting http://docs.oracle.com/javase/tutorial/uiswing/painting/

    Not to discourage you but this is a tricky process, To answer your question there is a similar post here Java Change shape of JPanel