/*
* AdjustFace.java
* This example implements a happy/sad face meter. The scrollbar is
* used to adjust the face. The class Face has a setSmile() method
* that takes real number from 0 to 1. The higher the value, the
* happier the face. The lower the value, the sadder the face.
*/
import java.awt.*;
import java.awt.event.*;
public class AdjustFace extends
java.applet.Applet implements AdjustmentListener{
Scrollbar sb = new
Scrollbar(Scrollbar.HORIZONTAL, 99, 1, 0, 100);
Face face = new Face();
public void init () {
// Listen for events
sb.addAdjustmentListener(this);
//
Layout components
setLayout(new BorderLayout());
add(face, BorderLayout.CENTER);
add(sb, BorderLayout.SOUTH);
}
// Handle adjustment
events.
public void adjustmentValueChanged(AdjustmentEvent e) {
face.setSmile((e.getValue()-50)/50.0);
}
}
class Face extends Component{
double smile = 1.0;
public void paint(Graphics g){
int size = getSize().width;
//
Keep it square
if (size > getSize().height){
size =
getSize().height;
}
//
Paint yellow
g.setColor(Color.yellow);
g.fillOval(0,0,size-1,size-1);
//
Paint outline
g.setColor(Color.black);
g.drawOval(0,0,size-1,size-1);
g.drawOval(1,1,size-2,size-2);
//
Paint eyes
int eyew = (int)(size * 0.18);
int eyeh = Math.abs((int)(size*0.36*smile));
g.fillOval(size/3-eyew/2,
size/3-eyeh/2, eyew, eyeh);
g.fillOval(size*2/3-eyew,size/3-eyeh/2,eyew,
eyeh);
//
Paint mouth
int mouthw = size/3+eyew;
int mouthh = Math.abs((int)(size*0.4*smile));
int startAngle = smile < 0 ? 0:180;
int mouthy = size*2/3-mouthh/2;
//
If frown, move rectangle lower.
if (smile <0){
mouthy +=mouthh/2;
}
g.drawArc((size-mouthw)/2, mouthy, mouthw, mouthh, startAngle, 180);
g.drawArc((size-mouthw)/2, mouthy+1,
mouthw, mouthh, startAngle, 180);
}
// -1.0 is a frown, 1.0 is
smile
public void setSmile(double smile){
this.smile = smile;
repaint();
}
}