Search code examples
javaswinggraphics2d

Java Graphics2D mouse pattern drawing


I have a GUI with a panel where I draw. Whatever mouse pattern I do is repeated in every sector which is divided by two lines. However, I am able to do this because my paintComponen method does not invoke super.paintComponent. If I actually do invoke the method I get only a single point whenever i drag my mouse. How should i go about it?

enter image description here

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import javax.swing.JPanel;

public final class DisplayPanel extends JPanel
{

private boolean dragging;
private Point draw;
private Line2D sectorLine;
private int sectors;

public void init()
{

    DisplayListener listener = new DisplayListener();

    addMouseListener(listener);
    addMouseMotionListener(listener);
    setOpaque(true);
    setBackground(Color.BLACK);
    setSize(900,900);
    setVisible(true);
}

//performs the drawing on the display panel
public void paintComponent(Graphics g)
{
    //super.paintComponent(g);

    setBackground(Color.BLACK);


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

    sectorLine = new Line2D.Double(getWidth()/2, 0, getWidth()/2, getHeight());
    sectors = 12;

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

    //draws the doilie
    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);
        }

    }



}

private class DisplayListener extends MouseAdapter
{   
    public void mouseDragged(MouseEvent event)
    {
        dragging = true;
        draw = event.getPoint();
        repaint();
    }

    public void mouseReleased(MouseEvent event)
    {
        dragging = false;
    }

}


}

Solution

  • super.paintComponent() erases/clears the area before drawing, so you only see the point you current draw.

    If you want to draw the line the mouse dragged, you would have to store each drawn coordinate in a List, and then in paintComponent(), draw all the points again. Please be aware that this list could get very big, and thus eat a lot of memory, so you should probably think about limiting it somehow.