Set size of components in Swing?


#1

I am back with another Swing question. I think maybe there should be some Kotlin documentation for this somewhere… :thinking: but back to my question. How would I resize elements in Swing? I have tried Googling to find the answer, and have came back with none (or I would not be writing this). Please explain in detail because I am new to Swing. I also want to complement everyone who goes through here answering questions, and not voting down questions like on Stack Overflow, this community is so much better than the one that Stack Overflow has. You are all amazing people :heart:


#2

I think that what you are looking for is java.awt.Component.setSize(int, int) if you are resizing any component (JPane, JButton, etc), or java.awt.Window.setSize(int, int) for a JFrame or JWindow.

Here’s a working example:

import java.awt.FlowLayout
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import javax.swing.JButton
import javax.swing.JFrame
import javax.swing.JPanel

class SwingResize {

    private lateinit var mainFrame: JFrame
    private lateinit var controlPanel: JPanel

    init {
        prepareGUI()
    }

    private fun prepareGUI() {
        mainFrame = JFrame("Kotlin SWING Resize").apply {
            setSize(400, 400)
            layout = FlowLayout()
            isVisible = true

            addWindowListener(object : WindowAdapter() {
                override fun windowClosing(windowEvent: WindowEvent?) {
                    System.exit(0)
                }
            })
        }

        controlPanel = JPanel()
            .apply { layout = FlowLayout() }
            .also { mainFrame.add(it) }
    }

    fun show() {
        JButton("Resize").apply {
            var isResized = false
            addActionListener {
                if (isResized) mainFrame.setSize(400, 400) // Resize the JFrame to 400px * 400px
                else mainFrame.setSize(200, 200) // Resize the JFrame to 200px * 200px
                isResized = !isResized
            }
        }.also { controlPanel.add(it) }

        mainFrame.isVisible = true
    }
}

fun main(args: Array<String>) = SwingResize().show()

#3

Thank you, you are such a huge help to this community, I looked at your profile, and you are one of the more knowledgeable people outside of the JetBrains Team. You have dedicated so much time to helping other people, and you ask for nothing in return. Thank you.