Last active
May 27, 2019 11:57
-
-
Save ahmednasserpro/264ebc7647a9b4e7a23c93c7752dd057 to your computer and use it in GitHub Desktop.
Animation ball on curve
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.*; | |
import java.awt.event.*; | |
import javax.swing.*; | |
public class BallOnCurveFrame extends JFrame { | |
private BallOnCurvePanel curvePanel = new BallOnCurvePanel(); | |
BallOnCurveFrame() { | |
curvePanel.setBackground(Color.black); | |
add(curvePanel); | |
} | |
public static void main(String[] args) { | |
JFrame frame = new BallOnCurveFrame(); | |
frame.setTitle("Ball on Curve"); | |
frame.setSize(400, 250); | |
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
frame.setLocationRelativeTo(null); | |
frame.setVisible(true); | |
} | |
} | |
class BallOnCurvePanel extends JPanel { | |
private int n = -175; | |
private int position = -1; | |
private Timer timer = new Timer(25, new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
if (n == 175) { | |
position = -1; | |
} else if (n == -175) { | |
position = 1; | |
} | |
if (position == -1) { | |
n--; | |
} else if (position == 1) { | |
n++; | |
} | |
repaint(); | |
} | |
}); | |
public BallOnCurvePanel() { | |
timer.start(); | |
} | |
@Override | |
protected void paintComponent(Graphics g) { | |
super.paintComponent(g); | |
Polygon polygon = new Polygon(); | |
for (int x = -175; x <= 175; x++) { | |
polygon.addPoint(x + 200, 100 - (int) (50 * | |
Math.sin((x / 100.0) * 2 * Math.PI))); | |
} | |
g.drawPolyline(polygon.xpoints, polygon.ypoints, polygon.npoints); | |
g.setColor(Color.ORANGE); | |
if (n >= -175 && n <= 175) { | |
g.fillOval(n + 200 - 5, 100 - (int) (50 | |
* Math.sin((n / 100.0) * 2 * Math.PI)) - 5, 10, 10); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment