javakotlinjframegraphics2d

How to use graphics 2d in kotlin with paint()


I want to start making a 2d video game, and I found a tutorial in java. However I wanted to use kotlin because I heard it is better, I am new to java and kotlin programming and I needed to put this

Graphics2d g2 = Graphics2D(g)

In kotlin, I didn't find anyway by searching.

If you want to know(but I think it doesn't matter) The JPanel class file is here:

import java.awt.Color
import java.awt.Dimension
import java.awt.Graphics
import java.awt.Graphics2D
import javax.swing.JPanel


class GamePanel : JPanel(), Runnable{
    //Screen settings
    var originalTileSize = 16
    var scale = 3
    var tileSize = originalTileSize * scale
    var maxScreenCol = 16
    var maxScreenRow = 12
    var gameThread = Thread()
    var screenWidth = maxScreenCol * tileSize // 768
    var screenHeight = maxScreenRow * tileSize // 576 TO CHANGE????

    init {
        this.setPreferredSize(Dimension(screenWidth, screenHeight))
        this.setBackground(Color.BLACK)
        this.setDoubleBuffered(true)
    }

    // Game Thread code
    public fun startGameThread(){
        gameThread = Thread(this)
        gameThread.start()
    }

    // run the game loop
    public override fun run(){
        while (gameThread != null){
            update()
            repaint()
        }
    }

    public fun update(){
        // Nothing for now
    }

    public override fun paintComponent(g : Graphics) {
        super.paintComponent(g)
        Graphics2D g2 = Graphics2D(g)
    }
}

Solution

  • In Kotlin casting is performed using the as keyword, like:

    val g2 = g as Graphics2D
    

    You may also use a safe cast with as?, that returns null if the casting is not possible, instead of throwing an exception:

    override fun paintComponent(g: Graphics) {
        super.paintComponent(g)
        val g2 = g as? Graphics2D
        if (g2 != null) {
            // Use g2 as needed...
        }
    }