Skip to content

Instantly share code, notes, and snippets.

@Kwisses
Created October 3, 2017 20:13
Show Gist options
  • Save Kwisses/fd61bbaa9309f8da0d5f72b68cd406c4 to your computer and use it in GitHub Desktop.
Save Kwisses/fd61bbaa9309f8da0d5f72b68cd406c4 to your computer and use it in GitHub Desktop.
VisualMetronome - [Java]
package swingapplications;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// A visual metronome that displays 4/4 time count.
class VisualMetronome implements ActionListener, Runnable {
Thread t;
JLabel prompt;
JLabel count;
JButton start;
JTextField bpm;
int counter = 1;
boolean startFlag = false;
// Set all properties of the GUI.
VisualMetronome() {
JFrame frame = new JFrame("Visual Metronome");
frame.setLayout(new FlowLayout());
frame.setSize(375, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
prompt = new JLabel("Enter BPM and press Start.");
count = new JLabel("0");
start = new JButton("Start");
bpm = new JTextField(3);
count.setFont(new Font(count.getName(), Font.PLAIN, 50));
count.setBounds(100, 100, 50, 50);
bpm.setActionCommand("BPM");
bpm.setText("60");
frame.add(prompt);
frame.add(bpm);
frame.add(start);
frame.add(count);
start.addActionListener(this);
frame.setVisible(true);
}
// Handles Start/Stop button presses.
public void actionPerformed(ActionEvent ae) {
if(ae.getActionCommand().equals("Start") ||
ae.getActionCommand().equals("Stop")) {
if(!startFlag) {
// Set and run metronome count.
counter = 1;
t = new Thread(this);
startFlag = true;
start.setText("Stop");
t.start();
} else {
// Stop and terminate metronome count.
startFlag = false;
start.setText("Start");
t = null;
}
}
}
// Run the count on Thread t.
@Override
public void run() {
while(startFlag) {
// Handles count delay.
try {
Thread.sleep(1000 / (Integer.valueOf(bpm.getText()) / 60));
} catch(InterruptedException e) {
// ...
} catch(NumberFormatException|ArithmeticException e) {
bpm.setText("60");
}
// Stops count immediately after Stop button has been pushed.
if(startFlag) {
if(counter <= 4) {
count.setText(String.valueOf(counter++));
} else {
counter = 1;
count.setText(String.valueOf(counter++));
}
}
}
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new VisualMetronome();
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment