简体   繁体   English

“ paintComponent()”重新绘制

[英]“paintComponent()” repaint

I painted some figures using paintComponent() method: 我使用paintComponent()方法绘制了一些图形:

public void paintComponent(Graphics g){

        super.paintComponent(g);
        g.setColor(Color.BLUE);

        g.drawRect(50, 50, 50, 50);
        g.drawOval(60, 60, 60, 60);

        //repaint();
        //g.drawOval(10, 10, 10, 10); - nothing effect
}

But now I want to erase all these figures and paint some new figure. 但是现在我要删除所有这些数字并绘制一些新数字。 I don't know how i must do it? 我不知道该怎么办? Maybe I must use repaint() method but use it wrong? 也许我必须使用repaint()方法,但使用错误?

Java draws all the figures your describe in the paintComponent() , but only when this method returns . Java绘制您在paintComponent()描述的所有图形,但仅在此方法返回时绘制。 So you can't draw then hide some figures in this method for the same method call. 因此,对于同一方法调用,您无法在该方法中绘制然后隐藏一些图形。 This method needs to be called a first time with a set of figures to show, then another time with another set of figures. 第一次调用此方法时需要显示一组图形,然后再次调用该方法需要另一组图形。

Maybe something like: 也许像:

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.BLUE);

    if (drawFiguresX) {
        g.drawRect(50, 50, 50, 50);
        g.drawOval(60, 60, 60, 60);
    } else {
        g.drawOval(10, 10, 10, 10);
    }
}

Whatever you are writing in the paintComponent method will be painted each time that the method is called. 每次调用paintComponent方法时,无论您在书写什么内容,都将对其进行绘制。 Based on the description so far, the usual way of achieving what you want to achieve is to determine whether something should be painted or not: 根据到目前为止的描述,实现您想要实现的目标的通常方法是确定是否应该绘制某些东西:

class TheClass extends JComponent
{
    private boolean paintTheFirstThing = true;

    @Override
    protected void paintComponent(Graphics g){
        super.paintComponent(g);

        if (paintTheFirstThing)
        {
            g.setColor(Color.BLUE);
            g.drawRect(50, 50, 50, 50);
            g.drawOval(60, 60, 60, 60);
        }
        else
        {
            g.drawOval(10, 10, 10, 10)  
        }
    }

    void setPaintTheFirstThing(boolean p)
    {
        this.paintTheFirstThing = p;
        repaint();
    }
}

(This is only a sketch, showing the basic idea. Of course, when you want to paint many different things, you'll not create lots of boolean flags for them. The key point is that in your paintComponent method, you have to describe what should be painted at certain point in time) (这只是一个草图,显示了基本思想。当然,当您要绘制许多不同的东西时, 不会为它们创建很多布尔标志。关键是在paintComponent方法中,您必须描述在某个时间点应该画些什么

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

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