How can I make the placement of my objects relative to the size of the window using SpringLayout

187 Views Asked by At

I am coding this in Kotlin using Swing but I can work with any answers in Java as well.

I have a JFrame with a panel that uses the SpringLayout layout manager.

var layout = SpringLayout()
var frame = JFrame()
var mainPanel = JPanel(layout)

I want to split the screen in two. I know that there are other ways to do this, but I created two more JPanels. One will be on the top and one will be on the bottom.

var topPanel = JPanel()
var bottomPanel = JPanel()
//I've omitted ll of the objects inside these two panels.

I know how to get them on the top and bottom of the screen, but I want them to stay there when I change the screen's size. Currently I have this bit of code.

layout.putConstraint(SpringLayout.NORTH, bottomPanel, screenSize().height/2, SpringLayout.NORTH, mainPanel)

The screenSize method just returns the size of the JFrame. It only gets the size in that instance so it won't work for me anyway.

private fun screenSize(): Dimension = frame.size

I know that using Spring, I can set the objects to always be in the exact center of the screen using SpringLayout.VERTICAL_CENTER, for example. This means that Spring is able to update the object's position in real-time as the screen size changes. I want a more general version of this where I can, for example, set my bottomPanel's y position to be the screen height / 2. This would update the panel's position every time the screen changes, similar to how setting the position to ScreenLayout.VERTICAL_CENTER does but moved upwards. I also need to use this to set the panel's sizes, as I want them to each be the screen width / 2. I can get the screen width at any time, but once I set the bottomPanel's position to it, it only updates at that moment and then it just continues to use that value. Spring doesn't have a constant for the screen width or height as far as I know, so I can't plug one into the putConstraint method. I need some other alternative. I already considered a loop that just keeps updating it, but that would be extremely inefficient for this one task. I would like to solve this directly using SpringLayout functionality if possible.

0

There are 0 best solutions below