I'm building a simple drum machine app and wanted to try animating a slider to move in rhythm with the beat to show which 16th note of the bar the drum machine is on.
I've set up a sequencer that runs in a 16 beat loop with the javax.sound.midi api. The sound aspect of the program is working fine, but I want my slider at the bottom of the screen to cycle though the beats with what I'm hearing.
When I implemented a changeListener to the code the slider's position only updates when I click the slider with my mouse.
I've tried using the both slider's and the JPanels's updateUI, repaint, revalidate methods but nothing changes.
Is it actually possible to animate GUI elements in this way?
Im using the swing API
tickDisplaySlider.addChangeListener(e -> {
tickDisplaySlider.setValue((int)sequencer.getTickPosition());
tickDisplaySlider.repaint();
System.out.println(Thread.currentThread() + " is running");
});
To make sure UI moves in sync with the music make the Java sequencer fire events every 16th note. To achieve that add your own Midi Controller messages every 16th note in your sequence.
Register the sequencer to get notified of these controller messages during playback. Then the event handler can update the slider on the Event Dispatching Thread.
Here is the code: