Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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...
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading