view src/luan/modules/swing/Component.luan @ 1886:03a8924fe9bc

swing
author Franklin Schmidt <fschmidt@gmail.com>
date Wed, 09 Apr 2025 08:56:54 -0600
parents d1708f8d4923
children bea843af3422
line wrap: on
line source

local Luan = require "luan:Luan.luan"
local error = Luan.error
local type = Luan.type or error()
local set_metatable = Luan.set_metatable or error()
local ipairs = Luan.ipairs or error()
local Utils = require "luan:swing/Utils.luan"
local fail = Utils.fail or error()
local make_metatable = Utils.make_metatable or error()
local delete = Utils.delete or error()
local check_empty = Utils.check_empty or error()
local check_not_nil = Utils.check_not_nil or error()
local get_font = require("luan:swing/Font.luan").get or error()
require "java"
local JPanel = require "java:javax.swing.JPanel"
local Logging = require "luan:logging/Logging.luan"
local logger = Logging.logger "swing/Component"


local Component = {}

function Component.__index(component,key)
	if key == "foreground_color" then
		return component.java.getForeground()
	end
	if key == "border" then
		return component.java.getBorder()
	end
	return fail
end

function Component.__new_index(component,key,value)
	if key == "foreground_color" then
		component.java.setForeground(value)
		return
	end
	if key == "border" then
		component.java.setBorder(value)
		return
	end
	return fail
end

local mt = make_metatable(Component)

local function construct(component,props)
	check_not_nil(props)
	local jcomponent = component.java
	jcomponent.putClientProperty("luan",component)  -- don't gc
	local layout = delete(props,"layout")
	if layout~=nil then
		if type(layout) == "function" then
			layout = layout(component)
		end
		jcomponent.setLayout(layout)
	end
	local border = delete(props,"border")
	if border~=nil then jcomponent.setBorder(border) end
	local children = delete(props,"children")
	if children~=nil then
		for _, child in ipairs(children) do
			jcomponent.add(child.java)
		end
	end
	component.request_focus_in_window = jcomponent.requestFocusInWindow
	function component.set_font(font)
		if type(font) == "table" then
			font = get_font(font)
		end
		jcomponent.setFont(font)
	end
	component._dont_gc = {}
	function component.dont_gc(obj)
		component._dont_gc[obj] = true
	end
	component.set_layout = jcomponent.setLayout
	function component.add(el)
		jcomponent.add(el.java)
	end
	function component.add_all(list)
		for _, child in ipairs(list) do
			jcomponent.add(child.java)
		end
	end
	return component
end
Component.construct = construct

function Component.new_component(jcomponent)
	local component = { java = jcomponent }
	construct(component,{})
	set_metatable(component,mt)
	return component
end

function Component.new_panel(props)
	local panel = { java = JPanel.new() }
	construct(panel,props)
	check_empty(props)
	set_metatable(panel,mt)
	return panel
end

return Component