Search code examples
swingscalascala-swing

Changing Scala Swing ComboBox Items


I tried to implement a date selection using three ComboBox as shown below.

contents += new Label("Selected Date:")
val dayBox = new ComboBox(1 to 31)
contents += dayBox
val monthBox = new ComboBox(List("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))
contents += monthBox
listenTo(monthBox.selection)
reactions += {
    case SelectionChanged(`monthBox`) => Dialog.showMessage(ui, "Month changed.")
}
contents += new ComboBox(2011 to 2020)

How can I change the items in dayBox as I change the monthBox? I knew that the Dialog.showMessage part should be changed. But I am wondering how?

For example, when I change to Jan, Mar, May, Jul, Aug, Oct, Dec, the day should show 31, while 30 for others except 28 for Feb.


Solution

  • You have to use the peer JComboBox object of the ComboBox to change the items in it:

    scala> import swing.ComboBox
    import swing.ComboBox
    
    scala> val cb = new ComboBox(1 to 31)
    cb: scala.swing.ComboBox[Int] = scala.swing wrapper scala.swing.ComboBox$$anon$1[...]
    
    scala> cb.peer.getModel.getSize
    res6: Int = 31
    
    scala> cb.peer.setModel(ComboBox.newConstantModel(1 to 30))
    
    scala> cb.peer.getModel.getSize
    res8: Int = 30