在JComponent上绘制圆圈时repaint()的行为

时间:2019-04-01 13:20:20

标签: java swing

当我单击JComponent时,我有一个关于在JComponent上绘制画圆的任务,如果您单击现有的圆,它将打印一条消息。一切工作正常,不同之处在于我画的第一个圆圈在后面的圆圈不会出现时会带有黑色边框。

我认为这与repaint方法有关,但我似乎找不到发生的事情。

import javax.swing.*;
import java.awt.*;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;

public class GraphComponent extends JComponent {

    private int defaultWidth = 500;
    private int defaultHeight = 500;
    protected Point spot;
    protected int width = 50;
    protected int height = 50;
    private ArrayList<Ellipse2D> shapeList = new ArrayList();

    public GraphComponent() {
        super();
        this.setPreferredSize(new Dimension(defaultWidth,defaultHeight));

        addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                boolean contains = false;
                spot = e.getPoint();
                for (Shape shape : shapeList) {
                    if (shape.contains(spot)) {
                        System.out.println("WIN");
                        System.out.println();
                        contains = true;
                        break;
                    }
                }

                System.out.println();
                System.out.println(shapeList.contains(spot));
                if(contains == false){
                    shapeList.add(new Ellipse2D.Double(spot.x - width / 2,
                            spot.y - width / 2, width, height));
                }
                repaint();
            }
        });

        addMouseMotionListener(new MouseAdapter() {
            public void mouseDragged(MouseEvent e) {
                //moveSquare(e.getX(),e.getY());
            }
        });
    }


    public void paintComponent(Graphics gfx) {
        super.paintComponents(gfx);
        for (Ellipse2D shape : shapeList) {
            gfx.drawOval((int)shape.getX(), (int)shape.getY(),width,height);
            gfx.setColor(Color.YELLOW);
            gfx.fillOval((int)shape.getX(), (int)shape.getY(),width,height);
        }
    }
}

我希望所有圆圈看起来都一样,但是第一个创建的圆圈带有黑色边框

circles example

1 个答案:

答案 0 :(得分:2)

您正在使用唯一的Graphics对象,因此(从第一次迭代开始)对drawOval的第一次调用将使用默认的Graphics的颜色(黑色)进行绘制。 / p>

下次迭代将全部涂成黄色。

for (Ellipse2D shape : shapeList) {
    gfx.drawOval((int)shape.getX(), (int)shape.getY(),width,height);// BLACK (at first iteration, YELLOW for next ones)
    gfx.setColor(Color.YELLOW);// YELLOW (from now on)
    gfx.fillOval((int)shape.getX(), (int)shape.getY(),width,height);
}