Plotting a Sine Wave

import javax.swing.*;
import java.awt.*;

public class SineWavePlot extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        drawSineWave(g);
    }

    private void drawSineWave(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setColor(Color.BLUE);

        int width = getWidth();
        int height = getHeight();
        int midY = height / 2;

        double frequency = 16 * Math.PI / width;
        int amplitude = height / 4;

        int prevX = 0;
        int prevY = midY;

        for (int x = 1; x < width; x++) {
            int y = (int) (midY + amplitude * Math.sin(frequency * x));
            g2d.drawLine(prevX, prevY, x, y);
            prevX = x;
            prevY = y;
        }
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Sine Wave Plot");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.add(new SineWavePlot());
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(SineWavePlot::createAndShowGUI);
    }
}
Explanation
  1. Creating the Custom JPanel (SineWavePlot):

    • The SineWavePlot class extends JPanel and overrides the paintComponent method to perform custom drawing.
    • super.paintComponent(g) ensures that the panel is properly rendered before adding custom drawings.
  2. Drawing the Sine Wave:

    • Graphics2D is used for better control and rendering quality.
    • Anti-aliasing is enabled for smoother graphics.
    • The sine wave is drawn by calculating the y-coordinate for each x-coordinate based on the sine function.
    • A loop iterates through the x-coordinates and uses g2d.drawLine to connect consecutive points on the sine wave.
  3. Creating and Showing the GUI:

    • The createAndShowGUI method sets up the JFrame, adds the custom JPanel, and makes the frame visible.
    • The main method uses SwingUtilities.invokeLater to ensure the GUI creation and updates are handled on the Event Dispatch Thread.

This program creates a window displaying a sine wave. You can run this code to see the sine wave plotted using Java Swing.

Comments

Popular posts from this blog

KTU OOP LAB JAVA CSL 203 BTech CS S3 - Dr Binu V P

Syllabus and Practice Questions KTU OOPS Lab Java CSL 203

String Problems