3

I am having trouble creating a ButtonGroup containing radio buttons in the Scala Programming Language. The code I am using is as following:

val buttongroup = new ButtonGroup {
  buttons += new RadioButton("One")
  buttons += new RadioButton("Two")
}

and my code for displaying the button group is within a BorderPanel:

layout += new BoxPanel(Orientation.Vertical) {
  buttongroup
} -> BorderPanel.Position.West

However, nothing displays... I've consulted the API and I'm not sure what is wrong!!

MRN
  • 193
  • 1
  • 12

2 Answers2

2

You should add a list containing the buttons to the panel, not the buttongroup itself, e.g.:


val radios = List(new RadioButton("One"), new RadioButton("two"))
layout += new BoxPanel(Orientation.Vertical) {
  contents ++= radios         
}

See also this example in the scala swing package itself.

Arjan Blokzijl
  • 6,878
  • 2
  • 31
  • 27
  • Thanks for the help, I really appreciated it. Do you know why it is contents ++= opposed to contents += in this scenario. Sorry for the basic questions!! – MRN Sep 21 '11 at 04:10
  • contents is a (mutable) scala Buffer, see http://www.scala-lang.org/api/current/index.html#scala.collection.mutable.Buffer, ++= appends all elements in the given collection to the Buffer, while += appends only a single element to the buffer. – Arjan Blokzijl Sep 21 '11 at 04:43
  • Ok one more thing -- I promise. I'm trying to use a match to look at the various cases of the list against the Button Group, as similar to the example that you have provided. def selected = { buttonGroup.selected.get match { case 'buttonOne' => println("buttonONe") } } but it is giving me the error message that pattern type is not accepted with expected type, and that there are multiple markers at this line. Any idea what is up here? – MRN Sep 21 '11 at 04:52
  • In the snippet you provided it looks like you're using quotes in the pattern match. You should use backticks, i.e. `buttonOne` instead of 'buttonOne'. – Arjan Blokzijl Sep 21 '11 at 05:20
  • Note: While this does add buttons. it seems to miss the ButtonGroup part, which is needed to make the buttons exclusive. – Suma Jan 16 '15 at 10:28
1

While the button group makes the buttons mututaly exclusive, you still need to add individual buttons to the panel. You can use ButtonGroup.buttons to obtain the list of the buttons:

layout += new BoxPanel(Orientation.Vertical) {
  val buttongroup = new ButtonGroup {
    buttons += new RadioButton("One")
    buttons += new RadioButton("Two")
  }
  contents ++= buttongroup.buttons
} -> BorderPanel.Position.West

If you want the first button to be selected when the toolbar is created, you can add:

buttongroup.select(buttongroup.buttons.head)

Suma
  • 33,181
  • 16
  • 123
  • 191