/*
* Java编程思想 第4版
* 第22章 图形化用户界面
* 练习25:(8)在SineWave.java的基础上编写程序(一个使用SwingConsole类的应用程序),
* 在观察窗口画一条动态正弦波,它可以像示波器那样向后滚动,使用一个线程来控制动画。动
* 画的速度由java.swing.JSlider控件进行控制。
*/
package gui;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import static util.SwingConsole.*;
class SwingDraw extends JPanel implements Runnable{
private static final int POINT_NUM_PER_ONE_CYCLE = 200;
private int points;
private double[] sines;
private int[] pts;
private double dy;
private double dv ;
private Thread animator;
public void init (){
dy = 0.0;
dv = 0.005;
setBackground(new Color(0,127,127));
}
public void start (){
if (animator == null){
animator = new Thread( this );
animator.start();
}
}
public void run(){
while ( Thread.currentThread() == animator ){
repaint();
}
}
public void stop(){
animator = null;
}
@Override
public void paintComponent (Graphics g){
super.paintComponent(g);
points = POINT_NUM_PER_ONE_CYCLE*2;
sines = new double[points];
int maxHeight = getHeight();
pts = new int[points];
for(int i = 0;i<points;i++){
double radians = (Math.PI/POINT_NUM_PER_ONE_CYCLE)*i+dy;
sines[i] = Math.sin(radians);
pts[i]=(int)(sines[i]*maxHeight/2*.95+maxHeight/2);
}
int maxWidth = getWidth();
double hstep = (double)maxWidth/(double)points;
g.setColor(Color.RED);
for(int i = 1;i<points;i++){
int x1 = (int)((i-1)*hstep);
int x2 = (int)(i*hstep);
int y1 = pts[i-1];
int y2 = pts[i];
g.drawLine(x1, y1, x2, y2);
}
dy-=dv;
}
public void reSetDV(double newDV){
dv = newDV;
}
}
public class SwingWaveRun extends JFrame{
private SwingDraw sd = new SwingDraw();
private JSlider sDV = new JSlider(1,100,5);
private JTextField tFil = new JTextField(15);
public SwingWaveRun(){
sDV.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e){
double sDValue = ((JSlider)e.getSource()).getValue();
sd.reSetDV(sDValue/1000);
tFil.setText("dv = "+sDValue/1000);
}
});
add(sd);
sd.init();
sd.start();
add(BorderLayout.NORTH,sDV);
add(BorderLayout.SOUTH,tFil);
}
public static void main(String[] args) {
run(new SwingWaveRun(),700,450);
}
}