madcrazydrumma madcrazydrumma - 4 months ago 22
Java Question

"Animating" sine wave drawing

So I've made a simple sine wave in Java. I just wanted to know how I could possibly go about "animating" the wave to show a waveform movement.

Sine wave

Here is my code so far:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;
import javax.swing.Timer;

public class WavePane extends JPanel
{
int width = Waves.WIDTH, height = Waves.HEIGHT;
final int SPEED = 4; // 1000ms

Timer timer;
int phase;

public WavePane() {
phase = 0;
timer = new Timer(SPEED, new ActionListener() {
public void actionPerformed(ActionEvent event) {
phase++;
repaint();

if(phase >= 360) {
phase = 0;
}
}
});
timer.start();
}

public void paintComponent(Graphics g) {
super.paintComponent(g);

g.drawLine(0, height / 2, width, height / 2);

drawWave(g, width, height, phase);
}

private void drawWave(Graphics g, int width, int height, int phase) {
for(double x = -(width / 2); x <= (width / 2); x = x + 0.5) {
double y = 50 * Math.sin((x + phase) * (Math.PI / 180));

int x1 = (int)x;
int y1 = (int)y;

g.setColor(Color.BLUE);

g.drawLine((width / 2) + x1, (height / 2) - y1 - 1, (width / 2) + x1, (height / 2) - y1 - 1);
g.drawLine((width / 2) + x1, (height / 2) - y1, (width / 2) + x1, (height / 2) - y1);
g.drawLine((width / 2) + x1, (height / 2) - y1 + 1, (width / 2) + x1, (height / 2) - y1 + 1);
}
}
}


The code works and animation works too! But how can i make it smoother??

Answer

The repaint() method had to be called every update tick, to update whatever is to be rendered on the screen.

Comments