/* WaveApplet.java - mixes two sin waves */ import java.awt.*; public class WaveApplet extends java.applet.Applet { //class variables float ratio; float offset; float length; float coeff; Button b1; Button b2; Choice c; TextField t; //initialise applet public void init() { setBackground(Color.green); ratio = (float).5; offset = (float)0; length = (float)5; coeff = (float)1; add(b1 = new Button("-")); add(b2 = new Button("+")); add(c = new Choice()); c.addItem("ratio"); c.addItem("offset"); c.addItem("coeff"); c.addItem("length"); c.select(0); add("north", t = new TextField()); updateText(ratio); } //write current value to textField public void updateText(float value) { String valString = new String(); int val1, val2; val1 = (int)value; val2 = (int)((value - val1) * 100); valString = Integer.toString(val1) + "." + Integer.toString(val2); t.setText(valString); } //return y value for given x value float f(float x) { return (float)(((1 - ratio) * Math.sin(x) + ratio * Math.sin(coeff * x + offset / 57.3)) * (size().height - 60)) / 2; } //draw the wave public void paint(Graphics g) { int y0, y1; float mid = (float)(size().height / 2); float step = (float)6.28 * length / (float)size().width; g.setColor(Color.black); g.drawLine(0, (int)mid, size().width, (int)mid); for (int x = 0 ; x < size().width ; x++) { y0 = (int)(mid - f((float)x * step)); y1 = (int)(mid - f((float)(x + 1) * step)); g.setColor(Color.red); g.drawLine(x, y0, (x + 1), y1); } } public boolean action(Event e, Object o) { if (e.target == b1) { switch(c.getSelectedIndex()) { case 0: ratio -= (float).1; if (ratio < 0) ratio = 0; updateText(ratio); break; case 1: offset -= (float)15; if (offset < 0) offset = 0; updateText(offset); break; case 2: coeff -= (float).5; if (coeff < 1) coeff = 1; updateText(coeff); break; case 3: length -= 1; if (length < .5) length = (float).5; updateText(length); break; } repaint(); return true; } if (e.target == b2) { switch(c.getSelectedIndex()) { case 0: ratio += (float).1; if (ratio > 1) ratio = 1; updateText(ratio); break; case 1: offset += (float)15; if (offset > 1080) offset = 1080; updateText(offset); break; case 2: coeff += (float).5; if (coeff > 10) coeff = 10; updateText(coeff); break; case 3: length += 1; updateText(length); break; } repaint(); return true; } if (e.target == c) { switch(c.getSelectedIndex()) { case 0: updateText(ratio); break; case 1: updateText(offset); break; case 2: updateText(coeff); break; case 3: updateText(length); break; } return true; } return super.action(e, o); } }