简体   繁体   English

java drawOval重复的圆圈

[英]java drawOval repeated circles

三个圆圈

When redrawing circles, the window is not cleared; 重画圆圈时,窗口不会清除; the new circles get added to the existing content. 新圈子会添加到现有内容中。

The goal is to create three circle, one for each color. 目标是创建三个圆圈,每种颜色一个。

The thread calls move function which draws the circles with different radii. 线程调用move函数,该函数绘制半径不同的圆。

public void run() {
    try {
          while(true){
              box.removeAll();
              move();
              box.removeAll();
              sleep(500);
          }
    } catch (InterruptedException e) {
    }
}

public synchronized void move() {
    Graphics g = box.getGraphics();
    g.setXORMode(box.getBackground());

    x1= one.x + ofset;
    y1= one.y + ofset;

    System.out.println("My Point ("+ x1 + " , " + y1 +")" );

    g.setColor(Color.green);
    g.drawOval(pointA.x-(int)distance1, pointA.y-(int)distance1, (int)distance1*2, (int)distance1*2);

    g.setColor(Color.blue);
    g.drawOval(pointB.x-(int)distance2, pointB.y-(int)distance2, (int)distance2*2, (int)distance2*2);

    g.setColor(Color.red);
    g.drawOval(pointC.x-(int)distance3, pointC.y-(int)distance3, (int)distance3*2, (int)distance3*2);

    g.dispose();
}

First of all, your approach is not recommended. 首先,不建议您使用此方法。 But, if you only want a quick and dirty fix, you have to clear the panel before drawing the circles. 但是,如果您只想进行快速且肮脏的修复,则必须在绘制圆之前清除面板。

Graphics g = box.getGraphics();
g.clearRect(0, 0, box.getWidth(), box.getHeight()); // this should do it
g.setXORMode(box.getBackground());
Graphics g = box.getGraphics();

No. Don't use getGraphics(). 不。不要使用getGraphics()。 Any painting done with that Graphics object is only temporary and will be deleted any time Swing determines a component needs to be repainted. 用该Graphics对象完成的任何绘制只是临时的,并且在Swing确定需要重新绘制组件时将被删除。

For custom painting override the getPreferredSize() method of a JPanel: 对于自定义绘画,请重写JPanel的getPreferredSize()方法:

@Override
protected void paintComponent(Graphics g)
{
    super.paintComponent(g); // clears the background

    // add your custom painting here
}

Also, don't forget to override the getPreferredSize() method of your panel. 另外,不要忘记重写面板的getPreferredSize()方法。 Read the section from the Swing tutorial on Custom Painting for more information. 阅读Swing教程中有关Custom Paint的部分,以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM