By Alvin Alexander. Last updated: November 19, 2017
To center a window/frame in a Scala Swing application, add this line to your frame definition:
peer.setLocationRelativeTo(null)
Here’s what this looks like in the top
method definition inside a SimpleSwingApplication
:
def top = new MainFrame { title = "Convert Celsius / Fahrenheit" contents = new FlowPanel(celsius, new Label(" Celsius = "), fahrenheit, new Label(" Fahrenheit")) peer.setLocationRelativeTo(null) }
In case that doesn’t make sense, here’s the source code for a complete Scala Swing application:
package tests import scala.swing._ import scala.swing.event.EditDone import scala.swing.event.WindowActivated object Converter extends SimpleSwingApplication { def newField = new TextField { text = "0" columns = 5 } val celsius = newField val fahrenheit = newField def top = new MainFrame { title = "Convert Celsius / Fahrenheit" contents = new FlowPanel(celsius, new Label(" Celsius = "), fahrenheit, new Label(" Fahrenheit")) peer.setLocationRelativeTo(null) } listenTo(fahrenheit, celsius) reactions += { case EditDone(`fahrenheit`) => val f = Integer.parseInt(fahrenheit.text) val c = (f - 32) * 5 / 9 celsius.text = c.toString case EditDone(`celsius`) => val c = Integer.parseInt(celsius.text) val f = c * 9 / 5 + 32 fahrenheit.text = f.toString } }
At the moment that code is just a modified version of the celsius to fahrenheit converter you can find online (like this one at Artima), but it drives me crazy when windows don't open centered, so I thought this would be a relatively simple example.