Java Kotlin --> Plotting Two Curves on the Same Plot

AI Thread Summary
The discussion presents a Kotlin program that utilizes Java Swing and AWT to graph sine and cosine curves over the interval [0, 2π]. The program creates a user interface with a JFrame and JPanel, where the curves are rendered using the Graphics class. Key features include dynamic scaling of the graph to fit the window, drawing of axes, and grid lines for better visualization. The sine and cosine functions are plotted by iterating through calculated points, ensuring smooth connections between them. The output displays a red sine wave and a blue cosine wave, with axes labeled at 0, π, and 2π. The program demonstrates effective use of Kotlin for graphical applications, showcasing its capabilities in GUI development.
Messages
15,448
Reaction score
10,150
Here's a Kotlin program that uses Java Swing and Java AWT to plot sine and cosine curves for the interval [0,2π].

The program creates a window with a panel where both curves are drawn:
  • Uses JFrame and JPanel for GUI rendering.
  • Uses Graphics to draw the sine and cosine curves.
  • Automatically scales the graph to fit within the window.

Kotlin Code:​


[CODE lang="java" title="Using Kotlin to plot Sine and Cosine on the same Chart"]
import java.awt.*
import javax.swing.*
import kotlin.math.*

class SineCosinePlot : JPanel() {
private val padding = 50 // Padding around the plot area
private val steps = 100 // Number of points to plot

override fun paintComponent(g: Graphics) {
super.paintComponent(g)
val g2 = g as Graphics2D
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)

val width = width - 2 * padding
val height = height - 2 * padding
val centerX = padding
val centerY = height / 2 + padding

// Draw axes
g2.color = Color.BLACK
g2.stroke = BasicStroke(2f)
g2.drawLine(centerX, centerY, centerX + width, centerY) // X-axis
g2.drawLine(centerX, padding, centerX, centerY + height / 2) // Y-axis

// Draw grid
g2.color = Color.LIGHT_GRAY
for (i in 1..4) {
val x = centerX + i * width / 4
val y = centerY - i * height / 4
g2.drawLine(x, padding, x, centerY + height / 2) // Vertical grid
g2.drawLine(centerX, y, centerX + width, y) // Horizontal grid
}

// Draw sine and cosine curves
drawFunction(g2, centerX, centerY, width, height, Color.RED) { x -> sin(x) }
drawFunction(g2, centerX, centerY, width, height, Color.BLUE) { x -> cos(x) }

// Draw labels
g2.color = Color.BLACK
g2.font = Font("Arial", Font.BOLD, 14)
g2.drawString("0", centerX - 10, centerY + 15)
g2.drawString("π", centerX + width / 2 - 5, centerY + 15)
g2.drawString("2π", centerX + width - 10, centerY + 15)
g2.drawString("1", centerX - 20, padding)
g2.drawString("-1", centerX - 25, centerY + height / 2)
}

private fun drawFunction(
g2: Graphics2D, centerX: Int, centerY: Int, width: Int, height: Int, color: Color,
function: (Double) -> Double
) {
g2.color = color
g2.stroke = BasicStroke(2f)

val stepSize = (2 * Math.PI) / steps
val scaleX = width / (2 * Math.PI) // Scale X to fit 0 to 2π
val scaleY = height / 2.0 // Scale Y to fit -1 to 1

var prevX = centerX
var prevY = (centerY - function(0.0) * scaleY).toInt()

for (i in 1..steps) {
val x = i * stepSize
val screenX = (centerX + x * scaleX).toInt()
val screenY = (centerY - function(x) * scaleY).toInt()
g2.drawLine(prevX, prevY, screenX, screenY)
prevX = screenX
prevY = screenY
}
}
}

fun main() {
SwingUtilities.invokeLater {
val frame = JFrame("Sine & Cosine Plot")
frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
frame.setSize(800, 600)
frame.add(SineCosinePlot())
frame.isVisible = true
}
}
[/CODE]

Explanation:​

  1. paintComponent(Graphics g):
    • This method is overridden when drawing the sine and cosine curves.
  2. Axes Drawing:
    • Draws the x-axis and y-axis with labels for 0,𝜋, and 2𝜋.
  3. Sine and Cosine Curves:
    • The graph is drawn by iterating over screen pixels and mapping them to the sine/cosine function.
    • x values are scaled using SCALE_X, and
    • y values are scaled using SCALE_Y.
    • drawLine() is used to connect consecutive points smoothly.

Output:​

  • A red sine wave and a blue cosine wave are displayed in a window.
  • Axes labeled at 0,𝜋, and 2𝜋.
  • The graph scales dynamically to fit in the window.
Screenshot 2025-03-15 at 11.35.54 PM.png

Solution Credits​


Proposed by: @hagopbul
Coded by: @ChatGPT
Reviewed by: @jedishrfu
 
Last edited:
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
What percentage of programmers have learned to touch type? Have you? Do you think it's important, not just for programming, but for more-than-casual computer users generally? ChatGPT didn't have much on it ("Research indicates that less than 20% of people can touch type fluently, with many relying on the hunt-and-peck method for typing ."). 'Hunt-and-peck method' made me smile. It added, "For programmers, touch typing is a valuable skill that can enhance speed, accuracy, and focus. While...
I had a Microsoft Technical interview this past Friday, the question I was asked was this : How do you find the middle value for a dataset that is too big to fit in RAM? I was not able to figure this out during the interview, but I have been look in this all weekend and I read something online that said it can be done at O(N) using something called the counting sort histogram algorithm ( I did not learn that in my advanced data structures and algorithms class). I have watched some youtube...

Similar threads

Replies
0
Views
331
Replies
0
Views
319
Back
Top