Open1

Compose for Desktop で複数のウィンドウを開く【Kotlin】【Compose Multiplatform】

ろくおろくお

したかったこと

  • ボタンを押したら対応するウィンドウが開くアプリケーションの作成

ソースコード

import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.ui.window.ApplicationScope
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application

@Preview
fun main() = application{
    AppWindow(this)
}

@Composable
fun AppWindow(application: ApplicationScope){
    val windowList = listOf("Sample1", "Sample2", "Sample3")

    val isOpen = remember { mutableStateMapOf<String, Boolean>() }

    for(w in windowList){
        isOpen += w to false
    }

    Window(
        title = "Sample",
        onCloseRequest = { application.exitApplication() }
    ){
        Column{
            for(w in windowList){
                Button(
                    onClick = {
                        isOpen[w] = true
                    },
                    enabled = !isOpen[w]!!
                ){
                    Text("Click to open $w")
                }

                if(isOpen[w]!!){
                    Window(
                        onCloseRequest = {isOpen[w] = false},
                        title = w
                    ){
                        SampleWindow.window(w)
                    }
                }
            }
        }
    }
}

object SampleWindow {
    const val title = "Sample Window"

    @Composable
    fun window(msg: String){
        Text("It works $msg")
    }
}

画像