JLabel animation in JPanel

纵饮孤独 提交于 2019-12-04 19:28:41

I noticed that in order to animate JLabels across the screen I need to setlayout(null); and setbounds of the component and then to animate eventually setlocation(x,y);. Is this a best practice or a terrible way to animate a component?

Well, this is not entirely true. You can just play with the location and the label will move around the screen. However, if you ever resize the frame or anything then the layout manager will be invoked and the label will be repositioned and the location defined by the layout manager which in the case of a FlowLayout will be the top/left of the panel. Animation will then continue from that location. So in reality, yes, this is exactly what you need to do.

I find it the easiest way to do animation since Swing will automatically repaint the "last" location of the component (to restore the background) as well as paint the new location of the component. This is all achieved by a single setLocation() method.

Some people like to do custom painting by drawing the image directly on the panel, but then you are responsible for clearing the old location of the image so the background is redrawn and then draw the image in the new location. I find this too much work.

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