The Programmers Guide To Kotlin - Using Swing
Written by Mike James   
Monday, 26 February 2024
Article Index
The Programmers Guide To Kotlin - Using Swing
Getters & Setters
Swing Events
The Program

Listing

The complete program is:

SwingUtilities.invokeLater {
       val myFrame=JFrame("Hello World")
       myFrame.setSize(300,200)
       myFrame.defaultCloseOperation=JFrame.EXIT_ON_CLOSE
       myFrame.layout=null        val myButton=JButton("Click Me")        myButton.bounds= Rectangle(15,50,150,50)        myButton.addActionListener  { e->         myButton.text= e.source.toString()
       }
       myFrame.add(myButton)
       myFrame.isVisible=true
   }

This is about as far as we can go with Swing. There is a lot more to learn, but it is essentially more of the same. You can find out about layouts and other components and build up your GUI bit by bit. A good way to create a Swing GUI in Kotlin is to use NetBeans to create a layout using its interactive drag-and-drop editor, and then copy and paste the Java into your project. If you are using IntelliJ it will offer to convert the Java to Kotlin and this works reasonably well.

Using Coroutines With Swing

As Swing is an asynchronous event driven UI, as are most Uis, you might be wondering, if it is possible to use coroutines? It is, but you need to use a dispatcher that runs on the correct thread. To do this you need to add the appropriate UI module:

kotlinx-coroutines-android

Dispatchers.Main context for Android applications.

Kotlinx-coroutines-javafx

Dispatchers.JavaFx context for JavaFX UI applications.

Kotlinx-coroutines-swing

Dispatchers.Swing context for Swing UI applications.

The Swing dispatcher uses the EDT to run coroutines and this is the one we need. To use it add:

dependencies {
 implementation(
  "org.jetbrains.kotlinx:kotlinx-
coroutines-core-jvm:1.5.0") implementation( "org.jetbrains.kotlinx:kotlinx-coroutines-swing:1.5.0") }

to the build.gradle file.

With this addition, we can simply rewrite the previous program as:

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.swing.Swing
import java.awt.Rectangle
import javax.swing.JButton
import javax.swing.JFrame
fun main() {
    runBlocking(context = Dispatchers.Swing) {
        println(Thread.currentThread().name)
        val myFrame = JFrame("Hello World")
        myFrame.setSize(300, 200)
        myFrame.defaultCloseOperation = 
JFrame.EXIT_ON_CLOSE myFrame.layout = null val myButton = JButton("Click Me") myButton.bounds = Rectangle(15, 50, 150, 50) myButton.addActionListener { e -> myButton.text = e.source.toString() } myFrame.add(myButton) myFrame.isVisible = true } println("main end") }

If you run this you will see main end printed, but the program will continue to run as the Swing event dispatcher keeps the thread occupied.

You can use coroutines in a Swing program in a very straightforward way as long as you remember to put code which modifies the UI onto the Swing dispatcher and other code on Main or one of the other dispatchers.

IDE Help

Final version in book

Problems With Types

Final version in book

The Kotlin Principle

Final version in book

kotlinlogo

Summary

 

  • Working with Java from Kotlin is usually essential due to the number of existing Java libraries that applications need to use. Working with Kotlin from Java is just as easy, but not as common.

  • Kotlin is a JVM language and it produces code which is very similar, if not identical, to Java. Using Java code from Kotlin is usually a matter of working out how its syntax maps to Java.

  • Java’s get and set methods are automatically converted to Kotlin properties. You can use the get/set methods or Kotlin’s syntax to work with them.

  • Kotlin can also convert Boolean functions that are named starting with is and have a setter starting with set as properties.

  • Swing is still a useful Java GUI library, but like most GUI libraries it runs its UI on a separate thread from the main program – the EDT.

  • Running code on the EDT is easy with the help of the SwingUtilities library.

  • An Interface with a Single Abstract Method, SAM, is how Java generally implements types of functions such as event handlers. The compiler automatically converts functions passed as SAM parameters to the appropriate interface implementation. This means you can pass lambdas where a SAM is required.

  • The SAM conversion means you can use lambdas as event handlers.

  • The IntelliJ and Android Studio IDEs provide lots of help in working with Java including lists of methods and properties that have been automatically converted.

  • Both IntelliJ and Android Studio can convert Java code files to Kotlin. You can also paste Java code into a Kotlin file with an optional conversion to Kotlin.

  • Java types that don’t have exact equivalents in Kotlin are shown in the IDEs as a type followed by !.

  • A particular problem with working with Java is its lack of non-nullable types. When working with a Java nullable, the best option is to treat it as a nullable Kotlin type.

  • Arrays in Java are primitive data types and Kotlin provides equivalents.

  • The Kotlin principle is to make use of good compile-time syntax to generate the same run-time behavior

This article is an extract from: 

Programmer's Guide To Kotlin Third Edition

kotlin3e360

You can buy it from: Amazon

Contents

  1. What makes Kotlin Special
  2. The Basics:Variables,Primitive Types and Functions 
  3. Control
         Extract: If and When 
  4. Strings and Arrays
  5. The Class & The Object ***NEW!
  6. Inheritance
  7. The Type Hierarchy
  8. Generics
  9. Collections, Iterators, Sequences & Ranges
        Extract: Iterators & Sequences 
  10. Advanced functions 
  11. Anonymous, Lamdas & Inline Functions
  12. Data classes, enums and destructuring
        Extract: Destructuring 
  13. Exceptions, Annotations & Reflection
  14. Coroutines
        Extract: Coroutines 
  15. Working with Java
        Extract: Using Swing
  16. Compose Multiplatform
        Extract: Compose Layout 

<ASIN:B0D8H4N8SK>

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

Banner


Gender Differences In Coding Style
13/11/2024

A novel investigation into the gender gap between men and women regarding coding ability was undertaken by Dr Siân Brooke. Her conclusion? There is a difference in the Python code [ ... ]



Copilot Improves Code Quality
27/11/2024

Findings from GitHub show that code authored with Copilot has increased functionality and improved readability, is of better quality, and receives higher approval rates than code authored without it.

 [ ... ]


More News

espbook

 

Comments




or email your comment to: comments@i-programmer.info

<ASIN:1871962544>



Last Updated ( Monday, 26 February 2024 )