Skip to content

Component Wrappers

Thosea edited this page Jun 22, 2025 · 2 revisions

Component Wrappers

Most of KSwing is made up of wrappers of Swing components. These functions are extensions of Container (like a JFrame or JPanel) and are added after being constructed. For example:

with(frame) { // with() is a kotlin builtin - see https://kotlinlang.org/docs/scope-functions.html
	// 'this' now refers to JFrame, which extends Container
	KLabel("Hi!") // creates JLabel and adds it to the frame
	KButton("Click me!") {
		// lambda is an extension, `this` now refers to JButton
		setToolTipText("You can click this button.")

		// this is a wrapper around addActionListener, see the listeners section for more
		kActionListener {
			println("Button clicked!")
		}
	} // JButton is added

	// They can also be nested
	KPanel {
		KVBox(addIndex = 0, addConstraints = "and have constraints") {
			// ...
		}
		KLabel("I'm in a panel!")
	}
}

There's also lazy variants of components - these are NOT extensions of Container and won't be added to the component they're called on. You can use them, for example, when passing a component to a JScrollPane:

KScrollPane(view = KLazyList {
	// ...
})

or when returning from a function

fun makeComponent() = KLazyPanel {
	// ...
}

Where possible, constructor overloads are replaced with default parameters.

By default, all components are given an alignmentX of Component.CENTER_ALIGNMENT. JLabel and JTextField have a horizontalAlingment of SwingConstants.CENTER. Don't want that? Change it in the setup lambda:

KLabel("Leading-aligned label") {
	alignmentX = Component.LEFT_ALIGNMENT
	horizontalAlignment = SwingConstants.LEADING
}

Special cases:

  • All Button components (JButton, JCheckBox, etc) have an optional buttonGroup parameter
  • Parameters are not provided for JEditorPane
  • JLabel have an optional custom HtmlDecorations parameter to wrap your text in HTML and add text-align
  • JList has a default parameter of DefaultListModel (not present in normal Swing)
  • Only lazy vairants of JMenuBar and JPopupMenu are provided because adding them to containers is usually a mistake
  • JPanel has an empty border by default, and also has constructors for all built-in layouts (i.e. KGridPanel)

Clone this wiki locally