Java Graphics2D鼠标图案绘制

Java Graphics2D mouse pattern drawing

我有一个 GUI,其中有一个面板供我绘制。无论我做什么鼠标模式,都会在被两条线分隔的每个扇区中重复出现。但是,我能够这样做是因为我的 paintComponen 方法不调用 super.paintComponent。如果我确实调用了该方法,那么每当我拖动鼠标时,我只会得到一个点。我该怎么办?

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;
    }

}


}

super.paintComponent() erases/clears绘制前的区域,所以你只能看到当前绘制的点。

如果要绘制鼠标拖动的线,则必须将绘制的每个坐标存储在一个列表中,然后在paintComponent()中重新绘制所有点。请注意,此列表可能会变得非常大,从而占用大量内存,因此您可能应该考虑以某种方式限制它。