X

Geertjan's Blog

  • February 23, 2012

Java Visual Playback Component

Geertjan Wielenga
Product Manager

For java.net/projects/nbjfuguesupport, it would be good to have a line that moves along the score while it is being played. Basically, a Visual Playback Component. 

I found the start of this online and slightly tweaked it. The red line on the left is currently to the left of the white line in the middle (which represents a note on the score). It is moving:

When it moves past the white line, the line becomes blue:

That means that I'm able to tell when the line moves past a note, which is exactly what is needed. As the line moves past a note, the note should be played.

The code:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Point2D;
import javax.swing.JPanel;
import javax.swing.Timer;
public class LineMovePanel extends JPanel {
private final int WIDTH = 400, HEIGHT = 200;
private final int DELAY = 20;
private Color color1, color2;
private Timer timer;
private int x1, x2, moveX, moveY;
private final int y1 = 0, y2 = HEIGHT;
public LineMovePanel() {
timer = new Timer(DELAY, new LineListener());
color1 = Color.red;
x1 = WIDTH / 2;
x2 = WIDTH / 2;
moveX = moveY = 3;
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground(Color.BLACK);
timer.start();
}
@Override
public void paintComponent(Graphics page) {
super.paintComponent(page);
Graphics2D g = (Graphics2D) page;
g.setPaint(new GradientPaint(
new Point2D.Double(WIDTH / 2, 0),
Color.red,
new Point2D.Double(WIDTH / 2 + 0.0001, 0),
Color.blue));
g.drawLine(x1, y1, x2, y2);
g.setColor(Color.pink);
g.drawLine(WIDTH / 2, 0, WIDTH / 2, HEIGHT);
}
private class LineListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent event) {
x1 += moveX;
x2 += moveX;
if (x1 <= 0 || x2 >= WIDTH) {
moveX = moveX * -1;
}
if ((x1 + 35) >= WIDTH / 2) {
color1 = Color.blue;
} else {
color1 = Color.red;
}
repaint();
}
}
}

Be the first to comment

Comments ( 0 )
Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.