https://kotlinlang.org logo
Title
a

Animesh Sahu

11/29/2020, 10:15 AM
is using
java.awt.Toolkit.getDefaultToolkit().screenSize
the correct way to obtain current screen dimensions? If yes, how'd ya obtain it in K/N in the future? Otherwise what's the correct way...
i

Igor Demin

11/29/2020, 10:39 AM
Because we can have multiple monitors, the correct way would be something like this:
AppWindowAmbient.current!!.window.graphicsConfiguration.device.displayMode.width
And we also need to listen changes of the screen size:
@Composable
private fun screenSize(): IntSize {
    val window = AppWindowAmbient.current!!.window
    var size by remember {
        mutableStateOf(
            IntSize(
                window.graphicsConfiguration.device.displayMode.width,
                window.graphicsConfiguration.device.displayMode.height,
            )
        )
    }

    onActive {
        val listener = AWTEventListener {
            size = IntSize(
                window.graphicsConfiguration.device.displayMode.width,
                window.graphicsConfiguration.device.displayMode.height,
            )
        }
        Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.PAINT_EVENT_MASK)

        onDispose {
            Toolkit.getDefaultToolkit().removeAWTEventListener(listener)
        }
    }

    return size
}
(listener code is from https://stackoverflow.com/questions/7455283/detect-screen-resolution-change-made-by-user-java-listener/13704277) In K/N it will be in a completely different way 🙂 . Maybe it is worth to provide a common API for this in the future.
👍 2
a

Animesh Sahu

11/29/2020, 1:12 PM
@Igor Demin In this case, the function is composable, so I cannot call it from other scope. I wanted to set the size of the primary window from the top-level function (main) in some sort of percentage of whole screen size...
i

Igor Demin

11/29/2020, 1:26 PM
In that case we can try this:
import androidx.compose.desktop.AppWindow
import javax.swing.SwingUtilities.invokeLater

fun main() = invokeLater {
    val window = AppWindow()
    val dpi = graphicsConfiguration.defaultTransform.scaleX.toFloat()
    val width = (graphicsConfiguration.device.displayMode.width / dpi).toInt()
    window.setSize(width / 3, 100)
    window.setWindowCentered()
    window.show {
        // Composable content
    }
}
👍 3