-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSineWave.java
More file actions
100 lines (72 loc) · 2.15 KB
/
SineWave.java
File metadata and controls
100 lines (72 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package gui;
/**
* RUN:
* javac -cp .; gui/SineWave.java && java -cp .; gui.SineWave
* OUTPUT:
*
*/
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import net.mindview.util.*;
public class SineWave extends JFrame {
private static final int WIDTH = 700;
private static final int HEIHGT = 400;
private SineDraw sines = new SineDraw();
private JSlider adjustCycles = new JSlider(1, 30, 5);
public SineWave() {
add(sines);
adjustCycles.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
sines.setCycles(
((JSlider) e.getSource()).getValue()
);
}
});
add(BorderLayout.SOUTH, adjustCycles);
}
public static void main(String[] args) {
SwingConsole.run(new SineWave(), WIDTH, HEIHGT);
}
}
class SineDraw extends JPanel {
private static final int SCALEFACTOR = 200;
private int cycles;
private int points;
private double[] sines;
private int[] pts;
public SineDraw() {
setCycles(5);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
int maxWidth = getWidth();
double hstep = (double)maxWidth / (double)points;
int maxHeight = getHeight();
pts = new int[points];
for (int i =0; i < points; i++) {
pts[i] = (int) (sines[i]*maxHeight/2 * 0.95 + maxHeight/2);
}
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);
}
}
public void setCycles(int newCycles) {
cycles = newCycles;
points = SCALEFACTOR * cycles * 2;
sines = new double[points];
for(int i = 0; i < points; i++) {
double radians = (Math.PI / SCALEFACTOR) * i;
sines[i] = Math.sin(radians);
}
repaint();
}
}