Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.Color;
- import java.awt.Graphics;
- import java.awt.Graphics2D;
- import java.awt.RenderingHints;
- import java.awt.geom.GeneralPath;
- import javax.swing.JFrame;
- import javax.swing.JPanel;
- import javax.swing.SwingUtilities;
- public class Sine {
- final double X_MIN = -2*Math.PI;
- final double X_MAX = 2*Math.PI;
- final double Y_MIN = -1.2;
- final double Y_MAX = 1.2;
- final double X_SHIFT = 0.2;
- final long X_SHIFT_TIME = 50; //ms
- final double N_POINTS = 1000;
- final double DX = (X_MAX-X_MIN)/(double) N_POINTS;
- final GeneralPath path = new GeneralPath();
- final JPanel panel = new JPanel(){
- protected void paintComponent(Graphics g) {
- super.paintComponent(g);
- Graphics2D g2 = (Graphics2D) g;
- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
- g2.setPaint(Color.RED);
- g2.draw(path);
- }
- };
- public static void main(String[] args) {
- SwingUtilities.invokeLater(() -> {
- Sine sine = new Sine();
- sine.createAndShowGUI();
- sine.start();
- });
- }
- void createAndShowGUI() {
- JFrame frame = new JFrame();
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setTitle("Sine wave");
- panel.setBackground(Color.WHITE);
- frame.add(panel);
- frame.setSize(500,300);
- frame.setVisible(true);
- }
- void start() {
- Thread th = new Thread(() -> {
- long count = 0;
- while( true ) {
- fillPath(count++ * X_SHIFT);
- panel.repaint();
- try {
- Thread.sleep(X_SHIFT_TIME);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- });
- th.setDaemon(true);
- th.start();
- }
- void fillPath(double xShift) {
- path.reset();
- path.moveTo(toCanvasX(X_MIN), toCanvasY(Math.sin(X_MIN + xShift)));
- for(int i=1; i<N_POINTS; i++) {
- double x = X_MIN + DX * i;
- double y = Math.sin(x + xShift);
- path.lineTo(toCanvasX(x), toCanvasY(y));
- }
- }
- double toCanvasX(double x) {
- double wPanel = (double) panel.getWidth();
- double xw = X_MAX - X_MIN;
- return (x+(xw/2))*(wPanel/xw);
- }
- double toCanvasY(double y) {
- double hPanel = (double) panel.getHeight();
- double yh = Y_MAX - Y_MIN;
- return (-y+(yh/2))*(hPanel/yh);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement