import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
public class SinusPanel extends JPanel {
static final long serialVersionUID = 01L;
private ClickListener myMouseListener;
private GeneralPath line;
private int scaleY, scaleX, width, height;
private int startX, startY, endX, endY;
public SinusPanel() {
super();
line = new GeneralPath();
myMouseListener = new ClickListener();
this.addMouseListener(myMouseListener);
this.addMouseWheelListener(myMouseListener);
endX = 0;
endY = 0;
startX = 0;
startY = 0;
scaleY = 20;
scaleX = 10;
width = 300;
height = 300;
this.setSize(width,height);
this.setBackground(new Color(0,150,0));
}
private class ClickListener implements MouseListener, MouseWheelListener {
private boolean startPoint = true;
public void mousePressed(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1) {
if(startPoint) {
startX = e.getPoint().x;
startY = e.getPoint().y;
startPoint = !startPoint;
endX = 0;
endY = 0;
} else {
endX = e.getPoint().x;
endY = e.getPoint().y;
startPoint = !startPoint;
}
repaint();
}
}
public void mouseEntered(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseWheelMoved(MouseWheelEvent e) {
if((e.getModifiersEx() & MouseEvent.SHIFT_DOWN_MASK)==MouseEvent.SHIFT_DOWN_MASK)
{
if(e.getWheelRotation() > 0) {
scaleY += 10;
repaint();
} else {
scaleY -= 10;
repaint();
}
} else {
if(e.getWheelRotation() > 0) {
scaleX += 1;
repaint();
} else {
scaleX -= 1;
repaint();
}
}
}
};
public void paint(Graphics g) {
super.paint(g);
double iter = 0.0;
int tmpX, tmpY;
// Einheitsvektor erstellen und Winkel zur X-Achse berechnen
double eX, eY;
eX = endX - startX;
eY = endY - startY;
double graphLength = vectorLength(eX, eY);
eX = eX / graphLength;
eY = eY / graphLength;
double arc = vectorArc(1.0, 0.0, eX, eY);
g.drawOval(startX-3, startY-3, 6,6);
if(endX != 0 || endY != 0)
{
g.drawOval(endX-3, endY-3, 6,6);
// Graph zeichnen
line.reset();
line.moveTo(startX, startY);
if(scaleX > 0)
while (iter*scaleX < graphLength) {
iter = iter + 0.1;
tmpX = (int) Math.round(iter*scaleX+startX);
tmpY = (int) Math.round(scaleY*Math.sin(iter)+startY);
line.lineTo(tmpX, tmpY);
}
AffineTransform rotation = AffineTransform.getRotateInstance(arc, startX, startY);
line.transform(rotation);
((Graphics2D) g).draw(line);
}
}
private double vectorLength(double x, double y) {
double tmpD = Math.sqrt(Math.pow(x, 2.0) + Math.pow(y, 2.0));
System.out.println("Length:"+tmpD);
return tmpD;
}
private double vectorArc(double x1, double y1, double x2, double y2) {
double tmpD = 0.0;
if(y1-y2 > 0) {
tmpD = (-1.0) * Math.acos((x1*x2+y1*y2)/vectorLength(x1,y1)*vectorLength(x2,y2));
} else {
tmpD = Math.acos((x1*x2+y1*y2)/vectorLength(x1,y1)*vectorLength(x2,y2));
}
System.out.println("Arc:"+tmpD);
return tmpD;
}
}