2015-09-07 11:44:36 -06:00
|
|
|
// ui/SineWave.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
|
|
|
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
// Drawing with Swing, using a JSlider.
|
|
|
|
import javax.swing.*;
|
|
|
|
import javax.swing.event.*;
|
|
|
|
import java.awt.*;
|
2015-11-11 20:20:04 -08:00
|
|
|
import static onjava.SwingConsole.*;
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
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 * .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();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public class SineWave extends JFrame {
|
|
|
|
private SineDraw sines = new SineDraw();
|
|
|
|
private JSlider adjustCycles = new JSlider(1, 30, 5);
|
|
|
|
public SineWave() {
|
|
|
|
add(sines);
|
|
|
|
adjustCycles.addChangeListener(e -> sines.setCycles(
|
|
|
|
((JSlider)e.getSource()).getValue()));
|
|
|
|
add(BorderLayout.SOUTH, adjustCycles);
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
|
|
run(new SineWave(), 700, 400);
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|