Leaving a trace while painting on a transparent JPanel

旧时模样 提交于 2019-12-02 07:41:27

Basically you need to repaint the entire component every time the paintComponent() method is called. This means you need to start from 0 and iterate up to the current value of x.

So your paintComponent() method should look something like:

public void paintComponent(Graphics g)
{
    super.paintComponent(g);

    x=x+1;
    y=y+1;

    for    (int i = 0; i < x; i++)
    {

        g.setColor(getForeground());
        //g.fillRect(x,y,x+1,y+1);
        g.fillRect(i,i,i+1,i+1);
    }
}

This means you don't need your panel0. I also change the code for creating panel1:

p1= new MyPanelB();
p1.setForeground(Color.RED);
p1.setBackground(Color.YELLOW);
f1.add(p1);

Even this code I posted for you is not correct. The x/y values should NOT be updated in the paintComponent() method. Try resizing the frame while your code is executing to see why?

Your ActionListener should invoke a method in your panel1 class to update property of the class to tell the paintComponent() how many times to iterate and paint the square when it is invoked. The the paintComponent() method should reference this property in the loop that I created.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!