A while back I made some animation for a song using p5.js. I thought that it would be great to make another video but instead do it with Swing. This is doable with JFrame and JPanel. I also imported JLabel in order to display some lyrics of the song I was making animation for as well as Timer which is important for controlling frame rate.
One of the great challenges of making this video involved the usage of Timer. I found that the playback of the video was often inconsistent and one of the things I had to do to keep it from slowing down was to increase the Timer value.
The first parameter is the frame-rate speed. Whatever this number is is the frequency in milliseconds that it refreshes. So if this number is low, it will refresh very frequently. I tried it with 5ms and it ran about twice as slow during screen capture, so I needed to find a frame-rate that was less frequent to improve performance. 36ms came very close to what I needed it to do.
JFrame and JPanel
There are a number of tutorials out there for doing animations in Swing. Sometimes you will have a class extending either the JFrame or JPanel class depending on what you are trying to accomplish. Some of them have some decent information, however I highly recommend looking at the Oracle Docs. There is an excellent tutorial on painting here with actual code that works: https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html. So if you’re unsure where to start, it might be a good place. Ideally if you are trying to make an animation like the one I made, you want to create a JFrame instance, and then add a new instance of a new class that will be extending JPanel to that JFrame.
Inside the class that extends JPanel, I have two critical methods which are the meat of where everything happens. Outside the methods there are a number of variables that are declared, including a value that I have ready to be incremented. In the actionPerformed() method, I increment my int x1 value. I also call repaint(); at the end.
In the paintComponent() method, everything that happens is a conditional based on the current value of x1. This makes it possible to time events with a value that increases at the same rate (a trick I learned from making a video with p5.js first).
From here I had all sorts of things happen such as altering rectangles, changing sizes and colors and changing the text of the JLabel from time to time.
One of the downsides to using Java Swing instead of something like p5.js is that when you make variables for widths and lengths and colors, it expects the value to be an int type. This makes precision a bit harder to achieve since you cannot use values with type double.
If you would like to see the end result of what I made, you may view it here: https://youtu.be/XD-lH9g_xb8
Also for comparison to by blog on p5.js, you can read that here: https://medium.com/@eselbeus/animation-logic-with-p5-js-85759a97134a