bertzzie
bertzzie

Reputation: 3568

Scala Swing Component Alignment

I'm learning how to build GUI using the standard Swing widget on Scala. Here's what I want to do:

enter image description here

I've had success in creating the components, but failed on aligning it. All of my components are aligned centered, not like what I want (Button1 on left, table on center, and button2 on right). I can't find much information about Scala's Swing either. Most of the search result is about Java's (which I don't know anything about). What should I do to force the alignment?

Here's the code:

ontents += new BoxPanel(Orientation.Vertical) {
    contents += new Button("Button 1")
    contents += new Table(3, 3)
    contents += new Button("Button 2")
}

The result:

enter image description here

Thanks before.

Upvotes: 3

Views: 2492

Answers (1)

Rogach
Rogach

Reputation: 27190

I usually use my own layout helpers (VBox and HBox), which make most of stuff very easy. But the following code achieves what you want using only standard library (I also took the liberty to add some borders and spacing between components):

import swing._
import Swing._
import java.awt.Color

new MainFrame {
  val button1 = new Button("Button 1")
  val button2 = new Button("Button 2")
  val table = new Table(4,3) {
    border = LineBorder(Color.BLACK)
  }
  contents = new BoxPanel(Orientation.Vertical) {
    border = EmptyBorder(10)
    contents += new BorderPanel {
      add(button1, BorderPanel.Position.West)
    }
    contents += VStrut(10)
    contents += table
    contents += VStrut(10)
    contents += new BorderPanel {
      add(button2, BorderPanel.Position.East)
    }
  }
  visible = true
}

(you can just paste the above into a file and run scala file.scala, it'll work)

Upvotes: 6

Related Questions