import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.event.*;
public class PulleyTest extends JPanel implements ChangeListener {
PulleyModel model = new PulleyModel(200,50,40,400);
Rectangle weight = new Rectangle(65, 40);
int bitterEndHeight = 100;
public void stateChanged(ChangeEvent e) {
bitterEndHeight = ((JSlider)e.getSource()).getValue();
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// draw pulley
g2.setPaint(Color.blue);
int dia = model.diameter;
Point p = model.loc;
double x = p.x - dia/2;
double y = p.y - dia/2;
Ellipse2D.Double pulley = new Ellipse2D.Double(x, y, dia, dia);
g2.draw(pulley);
// mark center
g2.setPaint(Color.orange);
g2.fill(new Ellipse2D.Double(p.x-2, p.y-2, 4, 4));
//
int h = getHeight();
int bitterLength = h - bitterEndHeight - p.y;
double loadLength = model.getLoadLength(bitterLength);
//System.out.printf("bitterLength = %d loadLength = %.1f%n",
// bitterLength, loadLength);
// check calculations
double totalLength = bitterLength + Math.PI*dia/2 + loadLength;
//System.out.printf("totalHeight = %.1f%n", totalLength);
// locate and draw weight
weight.setLocation(p.x+dia/2-weight.width/2, (int)(p.y+loadLength));
g2.setPaint(Color.green.darker());
g2.draw(weight);
// draw line
g2.setPaint(Color.black);
x = p.x-dia/2;
g2.draw(new Line2D.Double(x, p.y, x, p.y+bitterLength));
x = p.x+dia/2;
g2.draw(new Line2D.Double(x, p.y, x, p.y+loadLength));
}
private JSlider getSlider() {
JSlider slider = new JSlider(JSlider.VERTICAL,
10, 280, bitterEndHeight);
slider.addChangeListener(this);
return slider;
}
public static void main(String[] args) {
PulleyTest test = new PulleyTest();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(test);
f.add(test.getSlider(), "After");
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}
class PulleyModel {
int diameter;
Point loc;
int lineLength;
PulleyModel(int x, int y, int dia, int line) {
loc = new Point(x, y);
diameter = dia;
lineLength = line;
}
public double getLoadLength(int bitterLength) {
// loadLength = lineLength - bitterLength - circumference/2
return lineLength - bitterLength - Math.PI*diameter/2;
}
}