Skip to content
Thosea edited this page Jun 22, 2025 · 1 revision

States

KSwing has two state classes: KState and KNonnullState. They can hold any value and can have listeners for the value.

val pizzaOrders = KNonnullState(0)

KButton("Claim Pizza Prize") {
    isEnabled = false
    
    // called when pizzaOrders changes
    // since pizza orders starts at 0,
    // we don't need it to run now
    pizzaOrders.listen { count ->
		if(orders >= 10) {
			isEnabled = true
		}
	}
}

KLabel {
	// called immediately and when pizzaOrders changes
	// since the label starts with no text,
	// we need to initialize it now
	pizzaOrders.use { count ->
		text = "You've ordered $count pizzas!"
	}
    }
}

KButton("Order Pizza") {
	kActionListener {
		// use the 'value' field to change the state
		pizzaOrders.value++
	}
    }
}

To listen to or use multiple states at once, use kListenStates or kUseStates:

val pizzaOrders = KNonnullState(0)
val coins = KNonnullState(10)

KLabel {
	// called now and when pizzaOrders or coins changes
	kUseStates(pizzaOrders, coins) {
		// nothing is passed to the lambda, access values directly
		text = "You've ordered ${pizzaOrders.value} pizzas and have ${coins.value} coins left!"
	}
}

KButton("Order Pizza").kActionListener {
	if(coins.value < 1) {
		println("Not enough coins")
	} else {
		coins.value--
		pizzaOrders.value++
	}
}

Clone this wiki locally