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
Creating the Custom
JPanel
(SineWavePlot
):- The
SineWavePlot
class extendsJPanel
and overrides thepaintComponent
method to perform custom drawing. super.paintComponent(g)
ensures that the panel is properly rendered before adding custom drawings.
- The
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.
Creating and Showing the GUI:
- The
createAndShowGUI
method sets up theJFrame
, adds the customJPanel
, and makes the frame visible. - The
main
method usesSwingUtilities.invokeLater
to ensure the GUI creation and updates are handled on the Event Dispatch Thread.
- The
This program creates a window displaying a sine wave. You can run this code to see the sine wave plotted using Java Swing.
Comments
Post a Comment