所以我用Java制作了一个简单的正弦波。我只是想知道我怎么可能去做动画"动画"波形显示波形运动。
到目前为止,这是我的代码:
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);
}
}
}
代码工作和动画也有效!但是我怎样才能使它更顺畅 ??
答案 0 :(得分:0)
每次更新时都必须调用repaint()
方法,以更新屏幕上呈现的内容。